前段时间,由于公司项目中某个功能需要用到轮询的操作,所以参考了网上的一些资料,做了一个demo。主要方案是:AlarmManager +BroadcastReceiver +Service

首选需要获取AlarmManager,并包装要执行的服务:

    /**     * 开始轮询     */    public static void startPolling(Context context, int seconds, Class<?> cls, String action) {        //获取AlarmManager系统服务        AlarmManager manager = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        //包装需要执行Service的Intent        Intent intent = new Intent(context, cls);        intent.setAction(action);        PendingIntent pendingIntent = PendingIntent.getService(context, 0,                intent, PendingIntent.FLAG_UPDATE_CURRENT);        //触发服务的起始时间        long triggerAtTime = SystemClock.elapsedRealtime();        //使用AlarmManger的setRepeating方法设置定期执行的时间间隔(seconds秒)和需要执行的Service        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime,                seconds * 1000, pendingIntent);    }    /**     * 停止轮询服务     */    public static void stopPolling(Context context, Class<?> cls, String action) {        AlarmManager manager = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        Intent intent = new Intent(context, cls);        intent.setAction(action);        PendingIntent pendingIntent = PendingIntent.getService(context, 0,                intent, PendingIntent.FLAG_UPDATE_CURRENT);        //取消正在执行的服务        manager.cancel(pendingIntent);    }
然后我们需要在服务中执行获取数据的操作:

 @Override    public int onStartCommand(Intent intent, int flags, int startId) {       thread = new Thread(new Runnable() {            @Override            public void run() {                Intent intent = new Intent();                intent.setAction("CustomBroadcastReceiver");                intent.putExtra("data",++i);                sendBroadcast(intent);            }        });        thread.start();        return super.onStartCommand(intent, flags, startId);    }
在广播中,我定义了一个回调。广播接收到数据后,会执行回调,把数据传给activity:

 private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if(auctionListener == null) {                Toast.makeText(context,"监听器为空",Toast.LENGTH_SHORT).show();                return;            }else {                auctionListener.onUpdataAction(msg.what);            }        }    };    @Override    public void onReceive(Context context, Intent intent) {        this.context = context;        Message message = handler.obtainMessage();        message.what = intent.getIntExtra("data",0);        handler.sendMessage(message);    }
不过有一个问题,我明明在activity中设置了回调,仍然会执行监听器为空的操作,不明白为什么。知道的麻烦,回复一下,到底是什么原因?

然后是在activity中调用:

<span style="font-size:14px;">   @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView) findViewById(R.id.text);        receiver = new CustomBroadcastReceiver();        receiver.setOnAuctionListener(this);        IntentFilter intentFilter = new IntentFilter(CustomBroadcastReceiver.ACTION);        registerReceiver(receiver,intentFilter);        PollingUtils.startPolling(this,1,MyService.class,MyService.ACTION);    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(receiver);        PollingUtils.stopPolling(this,MyService.class,MyService.ACTION);    }    @Override    public void onUpdataAction(int data) {      textView.setText(data+"");    }</span>


更多相关文章

  1. android HttpClient+WebView 同步sessionId 和cookie
  2. Android中的跨进程回调
  3. Android(安卓)ubuntu10.04 源码下载和编译
  4. [ZZ][Android]使用bindService启动服务
  5. android 解析json数据(一)
  6. 在编译android如何来回切换JDK
  7. Android(安卓)Service相关
  8. Android使用HttpURLConnection请求网络资源
  9. Android位置服务--用户定位Location

随机推荐

  1. Android 7.0 IMS框架详解
  2. Android如何打印std::cout/printf(重定向s
  3. 不吹不黑!GitHub 上帮助人们学习编码的 12
  4. Android NDK开发学习(四)
  5. No.10 LVM快照的特点
  6. Android 适配7.0拍照、图库、裁剪
  7. android rotate
  8. Google将推出Android手机版Voice应用程序
  9. Android单元测试框架 Robolectric
  10. android selinux权限, Permission denied,