设备重启后运行服务

时间:2016-03-22 09:13:37

标签: android

即使用户重新启动了设备,我也希望我的其中一项服务能够运行。我尝试过这段代码,但没有成功。我该怎么办?请帮帮我。

谢谢!

MyService2.class:

public class MyService2 extends Service {
    private MyReceiver mR = null;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {
        mR = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
        registerReceiver(mR, intentFilter);
    }
}

MyReceiver.class

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            context.startService(new Intent(context, MyService.class));
            context.startService(new Intent(context,MyService2.class));
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您正在服务中注册BroadcastReciver,您尝试开始使用未注册的BroadcastReciver。

因此,请尝试在您的清单文件中注册广播接收器

<receiver android:name="your broadcast class">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter

答案 1 :(得分:0)

首先无需在服务中注册您的接收器。在Manifest中添加你的广播接收器。

赞:

<receiver android:name="your broadcast class">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>

请记住同时添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

当设备重新启动时,接收器将自动由系统执行,因为它在清单中声明。在您的接收器中,只需启动您的服务。

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        //add a log or toast to confirm the receive
        context.startService(new Intent(context, MyService2.class));
    }
}

}

public class MyService2 extends Service {
private MyReceiver mR = null;
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {
    // do what ever you wanted to do...
}

}