在手机重启后安排Android服务重新启动

3
我需要一个在我的应用程序中启动并永久运行的服务,即使用户重新启动手机,我的服务也会自动启动而无需运行我的应用程序。我编写了这段代码,但当用户重新启动手机时,我的服务不会重新启动!
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);

感谢您的帮助。
1个回答

4

在广播接收器中监听 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);
    }
}

此外,您还必须拥有以下权限: 参考资料:在Android中自动启动服务自动启动Android服务

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接