来自 BroadcastReceiver 的 startActivity() [英] startActivity() from BroadcastReceiver
问题描述
我正在尝试使用在 onPause() 方法中实现的以下 BroadcastReceiver 在充电时自动启动我的 nightclock 应用程序:
I am trying to autostart my nightclock application on charging using the following BroadcastReceiver implemented in the onPause() method:
BroadcastReceiver test = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
Intent i = new Intent(context, NightClock.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
};
registerReceiver(test, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
当插入 USB 电缆时触发 onReceive() 方法,但活动没有启动.但是日志显示:
The onReceive() method is fired when the USB-cable is plugged in, but the activity doesn't start. However the log shows this:
I/ActivityManager( 79): Starting activity: Intent { flg=0x10000000 cmp=com.meins.nightclock/.NightClock }
任何想法为什么日志说活动已开始,但没有任何反应?
Any ideas why the log says the activity is started, but nothing happens?
推荐答案
如果您的目标是在发送 ACTION_POWER_CONNECTED
广播时启动 NightClock
,您的使用 BroadcastReceiver
的方法很好.但是,不要从活动中注册它.相反,在清单中注册它:
If your goal is that you want NightClock
to be started whenever an ACTION_POWER_CONNECTED
broadcast is sent, your approach of using a BroadcastReceiver
is fine. However, do not register it from an activity. Rather, register it in the manifest:
<receiver android:name=".OnPowerReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
</intent-filter>
</receiver>
然后,将您的 BroadcastReceiver
作为公共 Java 类(此处命名为 OnPowerReceiver
,尽管您可以随意调用它),并让它调用 startActivity()
.
Then, have your BroadcastReceiver
as a public Java class (here named OnPowerReceiver
, though you can call it whatever you want), and have it call startActivity()
.
请记住,用户可能不希望您这样做.除了启动夜间时钟"之外,还有许多其他情况可以将手机连接到电源.我谦虚地建议您让用户通过主屏幕开始您的活动.
Bear in mind that users probably do not want you doing this. There are many other cases for connecting a phone to power besides starting a "night clock". I humbly suggest you simply let users start your activity via the home screen.
这篇关于来自 BroadcastReceiver 的 startActivity()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!