Android的报警管理与广播接收登记在code,而不是表现 [英] Android Alarm Manager with broadcast receiver registered in code rather than manifest

查看:103
本文介绍了Android的报警管理与广播接收登记在code,而不是表现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个闹钟在特定时间运行一些code。我已经成功实现与在清单中注册的广播接收器,但我理解的方式报警,此方法使用一个单独的类的广播接收机。

I want to use an alarm to run some code at a certain time. I have successfully implemented an alarm with the broadcast receiver registered in the manifest but the way i understand it, this method uses a separate class for the broadcast receiver.

我可以用这种方法来启动另一个活动,但我不能用它来运行我的主要活动的方法?

I can use this method to start another activity but I cant use it to run a method in my main activity?

(<一href="http://stackoverflow.com/questions/3122564/how-can-i-notify-a-running-activity-from-a-broadcast-receiver">how可我从广播接收器通知运行的活动?)

所以,我一直在尝试在上面的答案解释登记自己的广播接收器在我的主要活动。

So I have been trying to register my broadcast receiver in my main activity as explained in the answer above.

private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
        uploadDB();         
    }
};    

public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter();
    filter.addAction(null);

    this.registerReceiver(this.receiver, filter);
}

public void onPause() {
    super.onPause();

    this.unregisterReceiver(this.receiver);
}

不过,我一直无法得到这个报警经理的工作,我不能确定我应该如何报警意图链接到广播接收机。任何人都可以点我在活动中动态注册报警管理广播接收机的例子吗?或解释我会怎么做呢?

However I have been unable to get this to work with alarm manager, I am unsure as to how i should link the alarm intent to the broadcast receiver. Could anyone point me to an example of registering an alarm manager broadcast receiver dynamically in the activity? Or explain how i would do this?

推荐答案

这个怎么样?

Intent startIntent = new Intent("WhatEverYouWant");
PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, startPIntent);

// In Manifest.xml file
<receiver android:name="com.package.YourOnReceiver">
   <intent-filter>
       <action android:name="WhatEverYouWant" />
   </intent-filter>
</receiver>

所以,据我所知,你还是要申报清单中的接收器。我不知道,如果你可以将其设置为私有实例您的活动中。你可以声明的onReceive您的活动内,调用(如果BroadcastReceiver的有一个接口。我不知道它。)

So as far as I know you still have to declare the receiver in the Manifest. I'm not sure if you can set it to a private instance inside of your activity. You could declare an onReceive inside of your activity and call that (if the BroadcastReceiver has an interface. I don't know if it does.)

这篇关于Android的报警管理与广播接收登记在code,而不是表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆