在Android中重启时运行应用程序

时间:2016-04-27 04:10:16

标签: android

我想在手机重启时自动运行应用程序。我已将这些行添加到我的代码中:

public class BootComplete extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
        Intent serviceIntent = new Intent(context, MyActivity.class);
        context.startService(serviceIntent);
    }
}

我已将这些行添加到我的Manifest中:

<receiver
        android:name=".BootComplete"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

并获得许可:

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

MyActivity类只包含一些后台任务时,它可以正常工作。例如,当我想打开LED时。但是,当我想播放媒体(例如视频)时,它不起作用。只是说服务已经开始并且没有发挥任何作用。

我该如何解决?我必须在代码中添加任何内容吗?

2 个答案:

答案 0 :(得分:1)

问题不在于你的代码!这是关于Android设备的。

设备启动时,您会收到广播。但请注意,当您收到该广播时,SD卡仍在填充,您无法访问它。如果该媒体在SD卡上,则无法播放。

此外,您应该注意其他事项:如果用户在他/她的SD卡中安装您的应用程序,该广播接收器将永远不会触发。 因此,如果您想要防止某些设备出现问题,请在清单中为安装位置选择内部。

答案 1 :(得分:0)

BroadcastReceiver

中进行此更改
public class BootComplete extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
        Intent serviceIntent = new Intent(context, MyActivity.class);
        // Change is here...
        serviceInten.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(serviceIntent);
    }
}

在清单中:

<receiver
        android:name=".BootComplete"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter android:priority="500">
            <action android:name="android.intent.action.BOOT_COMPLETED" />

            <category android:name="android.intent.category.DEFAULT" />

            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
</receiver>

并保留许可。