注:
は、あなたのサービスが実行またはメソッドの下に使用されていませんチェックstopSelf()またはstopService()メソッドを使用してサービスを殺すまではサービスが生涯に実行されます。このドキュメントアクティビティクラスのdocs
public class MusicPlayerService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MusicPlayerService getService() {
// Return this instance of MusicPlayerService so clients can call public methods
return MusicPlayerService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** method for clients */
public void play() {
}
public void pause() {
}
public void stop() {
}
}
バインドservice.checkをcrerateする必要が音楽プレーヤーアプリの
public static boolean isServiceRunning(String serviceClassName){
final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
return true;
}
}
return false;
}
、 宣言mBoundブール変数、
boolean mBound;
はbindServiceImplementation
を追加
@Override
protected void onStart() {
super.onStart();
// Bind to MusicPlayerService
Intent intent = new Intent(this, MusicPlayerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
サービスのあなたのコードを投稿し、その後、あなたは以下のようなパブリックメソッドMusicPlayerServiceを呼び出すことができ、ServiceConnectionオブジェクトを初期化し、MusicPlayerServiceクラスと通信を行うようにするには
public void onButtonClick(View v) {
if (mBound) {
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
mService.play();
mService.pause();
mService.stop();
}
}
を
を作成します。 stopSelf()メソッドまたはstopService()メソッドを使用してサービスを終了するまで、サービスは永久に実行されます。 – Noorul