在安卓系统中开机自启一个应用程序

3
我想在手机重新启动时自动运行应用程序。我已经将以下代码添加到我的代码中:
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);
    }
}

我已经在我的清单文件中添加了以下行:

<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灯时。但是当我想要播放媒体(例如视频)时,它不起作用,只显示服务已启动,但没有播放任何内容。

我该如何解决它?是否需要向代码中添加任何内容?


你使用过Android Monitor查看Logcat吗? - Pourya MandiSanam
你为什么要把一个Activity称作Service呢? - JoxTraex
@JoxTraex 我是通过在 Stack 上搜索找到这些的。有更好的方法吗? - Alireza Amirshahi
什么?通过调用“startService”来启动活动。我以前从未尝试过。 - Kingfisher Phuoc
你为什么使用equalsIgnoreCase而不是equals - Kevin Krumwiede
2个回答

1
问题不在于你的代码!而是与安卓设备有关。
当设备启动时,你会收到广播。但请注意,当你接收到该广播时,SD卡仍在加载中,你无法访问它。如果媒体文件位于SD卡上,你将无法播放它。
另外,你还应该注意以下内容:如果用户将你的应用程序安装在他/她的SD卡中,则该广播接收器将永远不会触发。 因此,如果你想在某些设备上避免问题,在你的清单中,也要选择内部作为你的安装位置。

谢谢回答。我不想发布我的应用程序,我只想在我的设备上使用它。而且我的设备中没有存储卡。有什么办法可以做到这一点吗? - Alireza Amirshahi
请在接收者呼叫并且媒体未播放时分享您的日志记录。 - Omid Heshmatinia

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>

并且保持权限不变。


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