android 中PendingIntent 和AlarmManager
16lz
2021-01-23
想要让广播(服务,比如轮询)一直执行想要的操作怎么办呢,可以考虑使用PengdingIntent 和AlarmManager的搭配
在MainActivity中,编写自己想要实现的意图:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent("ELITOR_CLOCK"); intent.putExtra("msg","我获取到了信息"); //使用pendingIntent对Intent进行封装,发送给广播接受者 PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0); //使用AlarmManager进行时间的管理,是系统服务不能new AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); //设置要传递的pendingIntent am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5*1000,pendingIntent); }
根据注释内容已经可以看明白了,PendingIntent其实就是对Intent的封装,将其他的信息用一个大的PendingIntnet去传递,在PendingIntent中利用了AlarmManager的特性,定时的发送意图,那发送的意图,肯定要去处理意图,这里用一个广播去处理
public class MyRecevier extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("msg"); String action = intent.getAction(); Toast.makeText(context,message+"action:"+action,Toast.LENGTH_SHORT).show(); }}
重写Receiver方法,将数据从intent中取出来
记得要在AndroidManifest.xml中进行过滤才能够在Receiver中获取到数据(拦截到广播)
<receiver android:name=".MyRecevier" > <intent-filter > <action android:name="ELITOR_CLOCK"/> intent-filter> receiver>
这样就可以每隔一段时间在手机出现土司的效果了,也可以让后台的服务去执行操作
更多相关文章
- android 竖屏activity跳转横屏activity返回时数据消失
- js 判断当前操作系统 ios, android, 电脑端
- android 读取文件内容操作
- Android中进行HTTP操作
- android中ListView控件&&onItemClick事件中获取listView传递的数
- 在非主线程中不能操作主线程中的View
- android intent 传递各种结构数据
- android左右滑动加载分页以及动态加载数据
- Android数据共享 sharedPreferences 的使用方法