工作日常问题记录

254 阅读1分钟

startForegroundService

1 8.0版本后service 系统是不能设置前台service,在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。 如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      NotificationChannel channel = new NotificationChannel("11","ff", NotificationManager.IMPORTANCE_HIGH);
      NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      manager.createNotificationChannel(channel);
      Notification notification = new Notification.Builder(getApplicationContext(),"11").build();
      startForeground(1, notification);
  }
在onStartCommon 调用
service处于较高优先级而又不希望显示通知时,可以使用特殊技巧。如我们需要某一 ServiceX后台运行并且不能被杀掉,同时不希望被用户察觉,可以这样:
1,启动ServiceX并startForeground(id, notification)
2,立刻启动另一个ServiceY,也startForeground(id, notification),这里的id与ServiceX中startForeground的id一致;然后关闭在ServiceY中stopForeground(true)

ContentObserver 

onChange:监听短信收取用到content://sms/inbox协议,在小米8.0机型上 短信需要点击再返回APP才会触发此函数 , 采用content://sms/ 解决

定时任务类

  • timer+TimerTask
  • CountDownTimer
  • AlarmManger + (+Service+BarocastReceiver) 定时轮询6.0以上需要兼容 

client:
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, pendingIntent);
        } else {
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, Constant.UPLOAD_REPEAT_TIME, pendingIntent);
        }

service:
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent();
            intent.setAction("com.kxtx.pda.ACTION_UPLOAD_SCANDATA");
            PendingIntent pendingIntent = PendingIntent.getService(this, 202, intent, 0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + Constant.UPLOAD_REPEAT_TIME, pendingIntent);
        }
  • Handler.postDelayed
  • ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {……}}10, 20, TimeUnit.SECONDS)



待续……