1 : 使用前台进程是必须的
Intent intent = new Intent(MainActivity.this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
2 : 在service 里面发送前台可见通知
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: -----");
if (mBuilder == null) {
mBuilder = new NotificationCompat.Builder(this,"10");
NotificationManager notificationManager = (NotificationManager) getSystemService
(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("10", "senblo", NotificationManager.IMPORTANCE_DEFAULT);
// mBuilder.setChannelId("10");
notificationManager.createNotificationChannel(channel);
}
mBuilder.setLargeIcon(BitmapFactory.decodeResource(BaseApplication.getApplication().getResources(), R.mipmap.ic_launcher_app));
mBuilder.setSmallIcon(R.mipmap.ic_launcher_app);
mBuilder.setContentText("senblo sport running");
mBuilder.setContentTitle("senblo sport");
mBuilder.setOnlyAlertOnce(true);
Intent newIntent = new Intent(this, MainActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mBuilder.setContentIntent(PendingIntent.getActivity(this, 10, newIntent, PendingIntent.FLAG_UPDATE_CURRENT));
mBuilder.build().flags |= Notification.FLAG_ONGOING_EVENT;
mBuilder.build().flags |= Notification.FLAG_NO_CLEAR;
}
startForeground(10, mBuilder.build());
return START_STICKY;
}
3 : 最最最重要的是,循环发送通知
@SuppressLint("HandlerLeak")
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(mBuilder!=null){
Log.i(TAG, "handleMessage: -------2");
startForeground(10, mBuilder.build());
}
sendEmptyMessageDelayed(0,3*60*1000);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: --------");
mHandler.sendEmptyMessageDelayed(0,5000);
}
欧耶 \(^o^)/
版权声明:本文为vily_luky原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。