2017-11-16 7 views
0

私のアプリはバックグラウンドミュージックサービスを使用しています。 私のアプリケーションを終了するボタンがありますが、私のアプリケーションと私のサービスを閉じるための何かを見つけることができません。 自分のサービスを自分のアクティビティにバインドします。サービスを停止してアプリを終了

私が試した:

unbindService(serviceConnection); 
myService().stopSelf(); 
stopService(new Intent(this, MediaPlayer.class)); 

を絶対に何も機能しません!サービスは続けられます。

私のサービスを破壊するにはどうしたらよいですか?アプリケーションを閉じるにはどうすればいいですか?

のTx

EDIT:

私はのonCreateメソッド

Intent intent = new Intent(this, serviceClass); 
bindService(intent, serviceConnection, BIND_AUTO_CREATE); 

とMediaPlayerのクラスで

public class LocalBinder extends Binder { 
     public MediaPlayer getService() { 
      return MediaPlayer.this; 
     } 
    } 
public IBinder onBind(Intent intent) { 
    Log.i(TAG, "service bound"); 
    init(); 
    return mBinder; 
} 

そして、その中でこれを使用... しかし、私はいけません本当にサービスを開始する必要があるかどうかを確認します。サービスはすでにそれを開始バインド

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_NOT_STICKY; 
} 

は今、私はこれに

@Override 
public void onDestroy() { 
    player.stop(); 
    super.onDestroy(); 
} 

をしたonDestroyメソッドは、私はサービスのバインドを解除する場合にのみ動作します!全く このdoesntの仕事:

だから
 getService().stopSelf(); 
     this.stopService(new Intent(this, MediaPlayer.class)); 

、どのように私はサービスを停止することができ、どのように私は、アプリを閉じることができますか?

+0

サービスをどのように開始しますか? stopSelf()は、そのサービスから呼び出されたときにのみ動作します。 –

+0

"あなたのサービスを停止する"とはどういう意味ですか?それらのうちのいくつかはサービスを停止するでしょう。ただし、サービスを停止しても、サービスがプレーヤーを停止してonDestroyを適切に処理しない限り、音楽は停止しません。 –

+0

質問は明らかではありません...いくつかのコードと説明を追加してください。 – rafsanahmad007

答えて

0

これは私のアプリでやっていることです。アクティビティのonDestroy()メソッドは、アプリケーションを終了するときに呼び出されます。

private ServiceConnection musicServiceConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
     MusicService.LocalBinder binder = (MusicService.LocalBinder) service; 
     musicService = binder.getService(); 
     musicService.setCallbacks(MainActivity.this); 
     musicServiceBound = true; 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     Log.i(TAG, "MusicService service disconnected (unbinded)"); 
     musicServiceBound = false; 
    } 
}; 


@Override 
protected void onStart() { 
    super.onStart(); 
    Intent intent1 = new Intent(this, MusicService.class); 
    bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE); 
} 


@Override 
protected void onDestroy() { 
    super.onDestroy() 
    if(musicServiceBound){ 
     musicService.stopSelf(); 
     unbindService(musicServiceConnection); 
    } 
} 

あなたは()を使用して別のサービスを作成しているmyService()を、書きました。 プログラムでプログラムを終了するには、questionを参照してください。

+0

サービスオンデストロイですか? –

+1

アクティビティonDestroy –

+0

サービスはどこかで起動するのですか、それともバインドするだけですか? –

関連する問題