一、轮询服务启动
<span style="font-size:18px;">public class NewTaskService extends Service { public static final String ACTION = "com.dbjtech.myservice"; private Notification notification; private Notification.Builder builder; private NotificationManager mManager; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { initNotifiManager(); } @Override public void onStart(Intent intent, int startId) { new PollingThread().start(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void initNotifiManager() { LogUtil.debug("service", "asdfas"); mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent i; boolean flag = SharedPreferencesUtil.getBoolean(NewTaskService.this, "isLogin", false); if (flag) {//已经登录 i = new Intent(this, MainActivity.class); } else { i = new Intent(this, LoginActivity.class); } PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); long[] vibrate = {0, 1000, 1000, 1000};//延迟0ms,然后振动1000ms,再延迟1000ms,接着在振动1000ms。 Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg")); builder = new Notification.Builder(this) //创建消息提示框 .setTicker("显示屏幕顶端的状态栏") .setSmallIcon(R.drawable.ic_launcher) .setAutoCancel(true) .setContentIntent(pendingIntent) .setContentTitle("移动仓储") .setContentText("你有一条新任务") .setSound(soundUri) .setVibrate(vibrate); } private void showNotif() { System.out.println("开启一次接口轮询信息~~~");//查看标识 Map<String, Object> map = new HashMap<>(); map.put("userTicket", SharedPreferencesUtil.getString(this, "userTicket", "")); System.out.println(SharedPreferencesUtil.getString(this, "userTicket", "") + "userTicket"); <span style="white-space:pre"> </span>//轮询接口【<span style="background-color: rgb(255, 255, 255);"><span style="color:#6600cc;"> 接口使用缓存控件和消息弹栈 </span></span>】 NetWork.getJsonGetForXutil(Url.URL + "getTaskNotify.json?", map, new RequestCallBack<String>() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onSuccess(ResponseInfo<String> responseInfo) { String request = responseInfo.result; try { JSONObject jsonObject = new JSONObject(request); if (jsonObject != null) { boolean flag = jsonObject.getBoolean("success"); if (flag) { notification = builder.build(); mManager.notify(0, notification); } } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(HttpException e, String s) { } }); } /** * Polling thread * 模拟向Server轮询的异步线程 * * @Author Ryan * @Create 2013-7-13 上午10:18:34 */ int count = 0; class PollingThread extends Thread { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void run() { count++; //5分钟时间间隔 if (count % (5 * 60) == 0) { //外围环境设置1秒一轮询 showNotif(); } } } }</span>二、调用
在合适的位置上使用
PollingUtils.startPollingService(this, 1, NewTaskService.class, NewTaskService.ACTION);同时,因为是轮询服务,相对比较消耗资源,所以,在不必使用时,需要关闭服务。
人多不足以依赖,要生存只有靠自己。
深窥自己的心,而后发觉一切的奇迹在你自己。
凡事皆有终结,因此,耐心是赢得成功的一种手段。