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

标签 java android android-service

我需要在我的应用程序中提供一项服务,该服务可以在第一次启动并永远运行,即使用户重新启动他的手机,我的服务也会自动启动而无需运行我的应用程序。我写了这段代码,但是当用户重启他的手机时,我的服务没有再次启动!!

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();
    }
}

在主要 Activity 中,我开始这样的服务:

// start service
Intent service = new Intent(MainActivity.this, notifService.class);
MainActivity.this.startService(service);

谢谢你的帮助。

最佳答案

在 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 bootingAndroid Start Service on Boot Automatically

关于java - 安排Android服务在手机重启后重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644125/

相关文章:

java - 在 ImageView 中显示从数据库下载的图像

java.lang.Class: 在 java 程序中初始化 log4j 属性文件时出错

java - 一旦客户端确认,JMS 主题上的消息是否可用?

android - 当我创建一个新的 android 项目时出现错误

javascript - 定制 QR 扫描仪和阅读器

java - 如何复制 Liferay 中现有的组织角色并将其添加到已拥有原始角色的用户中?

java - 安卓数据绑定(bind) : Cannot resolve symbol

cordova - apache cordova 应用程序中的后台服务

android 服务通知 Activity 完成的最佳方式?

java - Android 中的 Activity 处理