想要让广播(服务,比如轮询)一直执行想要的操作怎么办呢,可以考虑使用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>

这样就可以每隔一段时间在手机出现土司的效果了,也可以让后台的服务去执行操作

更多相关文章

  1. android 竖屏activity跳转横屏activity返回时数据消失
  2. js 判断当前操作系统 ios, android, 电脑端
  3. android 读取文件内容操作
  4. Android中进行HTTP操作
  5. android中ListView控件&&onItemClick事件中获取listView传递的数
  6. 在非主线程中不能操作主线程中的View
  7. android intent 传递各种结构数据
  8. android左右滑动加载分页以及动态加载数据
  9. Android数据共享 sharedPreferences 的使用方法

随机推荐

  1. Android TextView textSize 单位问题
  2. Android 4.0允许用户禁用所有系统自带程
  3. PC&移动平台设备检测库(平台、版本、操作
  4. Android 工具类的两种写法---单例模式与
  5. 实现Android键盘的中英文适配
  6. Android View基础知识点
  7. android spinner控件自定义选择图层
  8. AndroidStudio中使用Jacoco统计Android应
  9. 【Android】Web开发之通过Apache接口处理
  10. Android “2019-09-11T00:00:00+09:00“