【发布时间】:2014-05-19 17:48:39
【问题描述】:
我有一个广播接收器,我想使用警报管理器启动另一个活动/服务。所以我想在我的广播接收器中设置一个警报管理器来动态启动活动。可能吗。请告诉我相应的指导。 谢谢
【问题讨论】:
标签: android broadcastreceiver alarmmanager
我有一个广播接收器,我想使用警报管理器启动另一个活动/服务。所以我想在我的广播接收器中设置一个警报管理器来动态启动活动。可能吗。请告诉我相应的指导。 谢谢
【问题讨论】:
标签: android broadcastreceiver alarmmanager
您想向我们展示一下您的代码吗?如果您不解释更多,我们无法准确回答。但是从广播接收器开始活动就像以通常的方式开始活动一样简单:
Intent intent = new Intent(context.getApplicationContext(), YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
在您的 onReceive() 中使用它......并且不要忘记将您的接收器注册到清单。
所以如果你想在重启 5 分钟后开始一个动作,它应该是这样的:
在您的 BootCompleted Receiver 中启动另一个 boradcastreceiver:
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,SecondBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 300000, pendingIntent); //5 minutes are 300000 MS
public class SecondBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i= new Intent(context, YourService.class);
context.startService(i);
}
}
public class YourService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//start here the Action You will do, 5 minutes after reboot
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
但这只是从头开始,我现在无法测试代码,这里没有 IDE。所以我不确定在你的 BootCompletedReceiver 中给 Intent 和 PendingIntent 提供上下文。
【讨论】: