サービスとブロードキャスト レシーバー クラスを作成しました。このサービスはタスクにバインドします。サービスとブロードキャスト レシーバーの両方を正常に開始できます。また、放送受信機を停止することもできます。しかし、サービスを停止することはできません。
これがサービスを開始および停止するための私のコードです。
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));
}
}
}
}