我正在尝试编写一个在手机启动时运行的服务,并且必须从 SD 卡读取数据。起初,我使用 android.intent.action.BOOT_COMPLETED
接收器,但切换到下面的 Intent 以确保 SD 卡已加载。
我的问题是,在我的 Nexus 7 上,它似乎没有收到 MEDIA_MOUNTED
Intent 。 Nexus 7 没有 SD 卡(但有单独的 SD 卡分区)。我还尝试了 BOOT_COMPLETED
Intent ,也获得了同样的运气。我已经在模拟器和 Thunderbolt 上测试了相同的代码,并且两种 Intent 都有效。
体现:
<receiver
android:name=".StartupReceiver"
android:enabled="true"
android:exported="true"
android:label="Start the NFS Automounter Service">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED"></action>
<data android:scheme="file"/>
<!-- <action android:name="android.intent.action.BOOT_COMPLETED"></action>-->
</intent-filter>
</receiver>
BroadcastReceiver
类:
public class StartupReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
//if ("android.intent.action.MEDIA_MOUNTED".equals(intent.getAction()))
//{
Log.d("NFS_Automounter", "Recieved Mount");
Intent serviceIntent = new Intent("com.ancantus.nfsautomounter.AutomountService");
context.startService(serviceIntent);
//}
}
}
我注释掉了 Intent 匹配,只是为了尝试记录该类是否被执行。
我唯一的预感是 Nexus 7 不会广播 MEDIA_MOUNTED
,因为它没有真正的 SD 卡;但我也无法接收 BOOT_COMPLETED
Intent 。
并搁置这个问题;是的,我确实拥有 BOOT_COMPLETED
权限。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
最佳答案
我必须输入该答案多少次才能开始出现在足够多的搜索结果中以便人们找到它?也许粗体大写字母会起作用:
从 ANDROID 3.1 开始,除非有人手动运行应用程序的其他组件(例如用户运行 Activity ),否则 BroadcastReceiver
根本无法工作。
这是在 documentation 中(尽管位置不太好),在 blog posts ,以及许多 StackOverflow 答案,例如:
- https://stackoverflow.com/a/9084771/115145
- https://stackoverflow.com/a/11865858/115145
- https://stackoverflow.com/a/11744499/115145
因此,向您的应用添加一个 Activity。无论如何,您需要一些 Activity ,用于控制后台操作的设置、文档、许可协议(protocol)、隐私政策等。
(注:我并不是真的对你大喊大叫——我只是感到沮丧,尽管我努力宣传这个消息,但这种情况不断出现......)
关于java - Nexus 7 上的广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255041/