在启动时启动计划活动的推荐方法?
我试图让预定的活动每隔一小时左右进行一次,所有这些都在后台工作。
现在我有一个广播接收器,可以在设备启动时接收。 BroadcastReceiver 为一个活动(称为 AlarmController)创建一个 PendingIntent,该活动创建了我需要的所有必要方法来使计划的活动进行。
然而,这似乎不起作用。 这就是我的 BroadcastReciever 类 onReceive{} 的样子并且与我的主要 Activity onCreate{} 相同(仅用于测试)
Intent intent = new Intent(serviceactivirt.this, AlarmController.class);
PendingIntent sender = PendingIntent.getActivity(serviceactivirt.this, 0, intent, 0);
try {
sender.send();
} catch (CanceledException e) {
Toast.makeText(getApplicationContext(), "FEJLSAN", Toast.LENGTH_LONG).show();
}
这实际上有效,除了我的应用在启动时崩溃,但计划的活动是在职的... 有什么想法吗?这是“这样做的方法”还是有更推荐的方法? 干杯!
解决方案:
我没有让 BroadcastReciever 调用 Activity,而是让 BroadcastReciever 启动一个 Service。并以编程方式和清单方式将我的活动更改为服务。 效果很好!
Im trying to make an scheduled activity go off every hour or so, all working in the background.
Right now i have a BroadcastReceiver that picks up when the device is booted.
The BroadcastReceiver creates a PendingIntent to an activity (Called AlarmController) that creates has all necessary methods that i need for making the scheduled activity to go off.
How ever, this doesnt seem to work.
This is how my BroadcastReciever class onReceive{} looks like and is indentical to my main activity onCreate{}(Only for testing)
Intent intent = new Intent(serviceactivirt.this, AlarmController.class);
PendingIntent sender = PendingIntent.getActivity(serviceactivirt.this, 0, intent, 0);
try {
sender.send();
} catch (CanceledException e) {
Toast.makeText(getApplicationContext(), "FEJLSAN", Toast.LENGTH_LONG).show();
}
This actually works, except that my app crashes at launch, but the scheduled activity is working...
Any ideas? Is this "The way to do it" or is there a more recommended way?
Cheers!
Solution:
Instead of having a BroadcastReciever calling an Activity, i made the BroadcastReciever starting a Service. And changed my Activity to a Service, programmaticly and in manifest.
Works great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请允许用户配置其他选项,例如使用
通知
,而不是被接管前台的活动中断。您只需要为每小时的事件设置
AlarmManager
时间表即可。AlarmManager
的PendingIntent
可以是通过getActivity()
获取的。如果您想启动一个 Activity,请调用
startActivity()
。不要创建PendingIntent
,然后立即send()
PendingIntent
。另外,摆脱
getApplicationContext()
并简单地使用this
。使用
adb logcat
、DDMS 或 Eclipse 中的 DDMS 透视图检查 LogCat 并查看与崩溃相关的堆栈跟踪。Please allow users to configure other options, such as using a
Notification
, rather than being interrupted by an activity taking over the foreground.You would only need that to set up an
AlarmManager
schedule for your hourly events. YourPendingIntent
for theAlarmManager
could be one you obtain viagetActivity()
.If you want to start an activity, call
startActivity()
. Do not create aPendingIntent
, then immediatelysend()
thePendingIntent
.Also, get rid of
getApplicationContext()
and simply usethis
.Use
adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look at the stack trace associated with your crash.