你需要在服务属性中的清单文件中添加"android:process=:any_name"。
例如,
<service android:name=".MyService"
android:process=":MyService"
android:enabled="true"/>
以下是我的Service类的代码。
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("onCreate", "onCreate");
Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("servicedestroy", "servicedestroy");
Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
}
});
}
},
0,
5000);
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
ServiceConnection
和服务绑定来保持服务不被销毁。 - Hemanth S