带有以代码而非清单注册的广播接收器的 Android 警报管理器

编程入门 行业动态 更新时间:2024-10-15 22:22:31
本文介绍了带有以代码而非清单注册的广播接收器的 Android 警报管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用闹钟在某个时间运行一些代码.我已经成功地使用在清单中注册的广播接收器实现了警报,但按照我的理解,此方法为广播接收器使用了一个单独的类.

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 警报管理器

本文发布于:2023-11-27 13:38:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638301.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接收器   管理器   而非   警报   清单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!