2013年1月13日 星期日

startActivity() from BroadcastReceiver


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));
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?
share|improve this question

60% accept rate
Please update your issue with more from LogCat -- a few lines before this one and a dozen or so lines after this one. Also, why FLAG_ACTIVITY_NEW_TASK? Also also, is the activity that registered thisBroadcastReceiver still around when ACTION_POWER_CONNECTED occurs? – CommonsWare Oct 3 '10 at 13:50
There are no more lines in LogCat when connecting to power. The BroadcastReceiver is registered in the same activity which it should start. This activity is still running in the background (the LogCat app has been brought to front). If this activity is killed in the taskmanager, the BroadcastReceiver doesn't seem to trigger at all. Is this approach to autostart my app wrong from the beginning? – Gubbel Oct 3 '10 at 14:47
feedback
If your goal is that you want NightClock to be started whenever an ACTION_POWER_CONNECTEDbroadcast 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.POWER_CONNECTED" />
</intent-filter>
</receiver>
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.
share|improve this answer

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...