带有以代码而非清单注册的广播接收器的 Android 警报管理器 [英] Android Alarm Manager with broadcast receiver registered in code rather than manifest
问题描述
我想使用闹钟在某个时间运行一些代码.我已经成功地使用在清单中注册的广播接收器实现了警报,但按照我的理解,此方法为广播接收器使用了一个单独的类.
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?
所以我一直在尝试在我的主要活动中注册我的广播接收器,如上面的答案所述.
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);
然后在您的 Manifest.xml
文件中:
And then in your Manifest.xml
file:
<receiver android:name="com.package.YourOnReceiver">
<intent-filter>
<action android:name="WhatEverYouWant" />
</intent-filter>
</receiver>
据我所知,你仍然需要在 Manifest 中声明接收者.我不确定您是否可以将其设置为您活动中的私有实例.您可以在您的活动中声明一个 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 警报管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!