如何停止我的应用程序在android中的服务?
问题描述:
我写了一个服务和广播接收器类。该服务与任务绑定。我可以成功启动服务和广播接收机。我也可以停止广播接收器。但我无法停止我的服务。如何停止我的应用程序在android中的服务?
这是我的代码来启动和停止服务。
public class Pedometer extends Activity {
private boolean mIsRunning;
public static Context mContext;
private StartAtBootServiceReceiver receiver;
private SharedPreferences prefs;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getBaseContext();
setContentView(R.layout.main);
prefs = getApplicationContext().getSharedPreferences(
"com.sa.sademo", Context.MODE_PRIVATE);
receiver = new StartAtBootServiceReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
mContext.registerReceiver(receiver, filter);
Button stopServiceAndBR = (Button) findViewById(R.id.stopServiceAndBR);
bankButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Pedometer.this.stopStepService();
}
});
startStepService();
}
public static Context getContext() {
return mContext;
}
@Override
protected void onResume() {
super.onResume();
if (mIsRunning) {
bindStepService();
}
}
@Override
protected void onPause() {
if (mIsRunning) {
unbindStepService();
}
super.onPause();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
private StepService mService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = ((StepService.StepBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
private void startStepService() {
mIsRunning = true;
startService(new Intent(Pedometer.this,
StepService.class));
}
private void bindStepService() {
bindService(new Intent(Pedometer.this,
StepService.class), mConnection, Context.BIND_AUTO_CREATE);
}
private void unbindStepService() {
unbindService(mConnection);
}
private void stopStepService() {
mIsRunning = false;
if (mService != null) {
PackageManager pm = mContext.getPackageManager();
ComponentName component = new ComponentName(mContext, StartAtBootServiceReceiver.class);
pm.setComponentEnabledSetting(component , PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);
unbindStepService();
mIsRunning = false;
if (mService != null) {
stopService(new Intent(Pedometer.this,
StepService.class));
}
}
}
}
答
您的服务中,你可以做:
//A variable to check
boolean cancel = false;
//a method to set this variable
public void cancel(){
cancel = true;
}
//inside of some point of your service you do:
while (yourCondition){
if (!cancel){
//do the service work
} else {
throw new StopServiceException(); // you have to create it.
}
}
内部与服务实例的aplication调用取消方法:
myService.cancel();