38
36

More than 5 years have passed since last update.

Serviceの挙動について

Posted at

経緯

Activityで再生している音楽を、アプリ終了しても再生し続けるようにしたい!

目的

  • アプリを終了してもサービスをstopするまで破棄されないようにする
  • ActivityからMediaPlayerを渡すために、bindを利用する

コード

MusicPlayService.java
public class MusicPlayService extends Service {

  private NotificationManager mNM;
  private final IBinder mBinder = new MusicPlayBinder();

  public class MusicPlayBinder extends Binder {
    public MusicPlayService getService() {
      return MusicPlayService.this;
    }
  }

  @Override
  public void onCreate() {
    Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
  }

  @Override
  public IBinder onBind(Intent intent) {
    Toast.makeText(this, "onBind", Toast.LENGTH_SHORT).show();
    // 通知押下時に、MusicPlayServiceのonStartCommandを呼び出すためのintent
    Intent notificationIntent = new Intent(this, MusicPlayService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, notificationIntent, 0);
    // サービスを永続化するために、通知を作成する
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
    builder.setContentIntent(pendingIntent);
    builder.setTicker("準備中");
    builder.setContentTitle("title");
    builder.setContentText("text");
    builder.setSmallIcon(android.R.drawable.ic_dialog_info);
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNM.notify(R.string.service_music_play, builder.build());
    // サービス永続化
    startForeground(R.string.service_music_play, builder.build());
    return mBinder;
  }

  @Override
  public void onDestroy() {
    Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
  }

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

}


まとめ

  • Activity側

    • startService(new Intent(this, MusicPlayService.class));
      • bindのみだとコネクションしているアクティビティ破棄時にサービスが終わる
      • サービスを起動しておく(stopServiceまで終わらない)
    • bindService(new Intent(this, MusicPlayService.class), mConnection, BIND_AUTO_CREATE);
      • コネクションを利用してデータを引数で簡単に渡せるのでbindを利用している
      • bindは永続化に必須ではない
  • Service側

    • startForeground(R.string.service_music_play, builder.build());
      • これに通知を渡すと、通知バーに表示され続ける(サービス終わるまで)
      • これが無いと、ホーム長押し→アプリスワイプでキル(GalaxyS4)するとサービス終わる
  • サービスの止め方

    • startのみの場合→stopすれば止まる
    • bindのみの場合→unbind or アクティビティ破棄
    • startとbindの両方を利用した場合→両方止める必要がある
38
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
36