2013年9月21日土曜日

Androidで強制終了されにくいサービスを作る

Androidでサービスを作ると、OSによって強制終了されてしまうがなるべく強制終了されにくいサービスを作る方法


○AndroidManifest.xmlへ記述

    <application ~

        <service android:name="jp.blogspot.stella_house_software.sampleservice.MainService" />


○Activityからサービスのインテントを起動する

Intent intent = new Intent();
intent.setClass(getApplicationContext(), MainService.class);
startService(intent);


○サービス本体

package jp.blogspot.stella_house_software.sampleservice;

import android.support.v4.app.NotificationCompat;

public class MainService extends Service  {



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("tag_debug", "[onStartCommand]");

//Notification notification = new Notification.Builder(this)
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("content title")
.setContentText("content text")
.setSmallIcon(R.drawable.ic_launcher)
.build();

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);

startForeground(1,notification);

return START_STICKY;
}
}

ポイントは、
・startForeground(1,notification);を入れる。
・サービスの onStartCommand を START_STICKY で returnする。


0 件のコメント:

コメントを投稿