【问题标题】:Setting AlarmManager in a Broadcast Receiver to call another activity/service在广播接收器中设置 AlarmManager 以调用另一个活动/服务
【发布时间】:2014-05-19 17:48:39
【问题描述】:

我有一个广播接收器,我想使用警报管理器启动另一个活动/服务。所以我想在我的广播接收器中设置一个警报管理器来动态启动活动。可能吗。请告诉我相应的指导。 谢谢

【问题讨论】:

    标签: android broadcastreceiver alarmmanager


    【解决方案1】:

    您想向我们展示一下您的代码吗?如果您不解释更多,我们无法准确回答。但是从广播接收器开始活动就像以通常的方式开始活动一样简单:

       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 提供上下文。

    【讨论】:

    • 我想从 alarmManagaer 启动我的服务/活动,并且该警报管理器必须在广播接收器中。例如,我有一个工作广播接收器用于重新启动。随着 OnRecieve() 中的移动重启代码被执行所以我的问题是我想在移动重启 5 分钟后安排服务。所以我应该有一个alam manager,它会在手机重启后启动服务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多