Android轮询机制

我记得我开始使用轮询是在做直播项目的时候,当时是在直播间中用来做弹幕的功能的。

在android中可以实现轮询的方式有很多,比如有handle,广播,观察者模式等等,而我最常用的方法是使用AlarmManager+Service+Thread来实现我们的轮询服务。

AlarmManager在Android中主要用来定时处理一个事件或是定期处理一个事件,比如闹钟应用就是使用AlarmManager来实现的,我们今天要使用AlarmManager的定期执行功能来实现轮询的功能。对于定期执行任务也可以用Timer和TimerTask来实现,也可以开一个Service在Thread里面以while循环来实现。但最好的方案还是选用AlarmManager,这里涉及一个Android系统锁的机制,即系统在检测到一段时间没有活跃以后,会关闭一些不必要的服务来减少资源和电量消耗。使用Timer和Service来实现的话很可能出现的情况就是屏幕熄灭后一段时间,服务就被停止了,当然轮询也就被停止了。那么接下来就开始使用AlarmManager+Service+Thread来实现我们的轮询服务吧!

首先新建轮询工具类PollingUtils.Java

public class PollingUtils {

//开启轮询服务

public static void startPollingService(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 stopPollingService(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);

}

}

第二步就是构建轮询任务执行PollingService.java

public class PollingService extends Service {

public static final String ACTION = "com.ryantang.service.PollingService";

private Notification mNotification;

private NotificationManager mManager;

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public void onCreate() {

initNotifiManager();

}

@Override

public void onStart(Intent intent, int startId) {

new PollingThread().start();

}

//初始化通知栏配置

private void initNotifiManager() {

mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

int icon = R.drawable.ic_launcher;

mNotification = new Notification();

mNotification.icon = icon;

mNotification.tickerText = "New Message";

mNotification.defaults |= Notification.DEFAULT_SOUND;

mNotification.flags = Notification.FLAG_AUTO_CANCEL;

}

//弹出Notification

private void showNotification() {

mNotification.when = System.currentTimeMillis();

//Navigator to the new activity when click the notification title

Intent i = new Intent(this, MessageActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,

Intent.FLAG_ACTIVITY_NEW_TASK);

mNotification.setLatestEventInfo(this,

getResources().getString(R.string.app_name), "You have new message!", pendingIntent);

mManager.notify(0, mNotification);

}

/**

* Polling thread

* 模拟向Server轮询的异步线程

* @Author Ryan

* @Create 2013-7-13 上午10:18:34

*/

int count = 0;

class PollingThread extends Thread {

@Override

public void run() {

System.out.println("Polling...");

count ++;

//当计数能被5整除时弹出通知

if (count % 5 == 0) {

showNotification();

System.out.println("New message!");

}

}

}

@Override

public void onDestroy() {

super.onDestroy();

System.out.println("Service:onDestroy");

}

}

最后就是在MainActivity.java中开启和停止PollingService

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//Start polling service

System.out.println("Start polling service...");

PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);

}

@Override

protected void onDestroy() {

super.onDestroy();

//Stop polling service

System.out.println("Stop polling service...");

PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文出处: http://www.androidchina.net/6174.html Notification在...
    木木00阅读 12,393评论 3 32
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • #Android 基础知识点总结 ---------- ##1.adb - android debug bridg...
    Mythqian阅读 3,360评论 2 11
  • 本人初学Android,最近做了一个实现安卓简单音乐播放功能的播放器,收获不少,于是便记录下来自己的思路与知识总结...
    落日柳风阅读 19,222评论 2 41
  • 他们都喜欢民谣了,可是他们并不伤感,该浪的还是在浪。我却喜欢电子了,可是我并不能嗨起来,该伤感的还是在伤感。 她勾...
    柘诗阅读 294评论 0 0