我需要在我的应用中首次启动并永久运行的服务,即使用户重启手机,我的服务也会自动启动,而无需运行我的应用。我写这段代码但是当用户重启他的手机时,我的服务不会重新开始!!
public class notifService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
在主要活动中,我开始这样的服务:
// start service
Intent service = new Intent(MainActivity.this, notifService.class);
MainActivity.this.startService(service);
谢谢你的帮助。
答案 0 :(得分:4)
在BroadcastReceiver中收听android.intent.action.BOOT_COMPLETED
并启动您的服务。
例如
public class YourDefinedBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, notifService.class);
context.startService(service);
}
}
此外,您必须持有权限:
参考:Automatically starting Services in Android after booting和Android Start Service on Boot Automatically