|
@@ -0,0 +1,84 @@
|
|
|
+package xn.update.service;
|
|
|
+
|
|
|
+import android.app.Notification;
|
|
|
+import android.app.NotificationChannel;
|
|
|
+import android.app.NotificationManager;
|
|
|
+import android.app.Service;
|
|
|
+import android.content.Intent;
|
|
|
+import android.content.IntentFilter;
|
|
|
+import android.os.Build;
|
|
|
+import android.os.IBinder;
|
|
|
+
|
|
|
+import androidx.annotation.Nullable;
|
|
|
+import androidx.core.app.NotificationCompat;
|
|
|
+
|
|
|
+import com.blankj.utilcode.util.LogUtils;
|
|
|
+
|
|
|
+import xn.update.R;
|
|
|
+import xn.update.broadcast.TimeTickReceiver;
|
|
|
+
|
|
|
+public class TaskService extends Service {
|
|
|
+
|
|
|
+ private TimeTickReceiver timeTickReceiver;
|
|
|
+
|
|
|
+ @Nullable
|
|
|
+ @Override
|
|
|
+ public IBinder onBind(Intent intent) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onCreate() {
|
|
|
+ super.onCreate();
|
|
|
+ createNotificationChannel();
|
|
|
+ LogUtils.d(getClass().getName(), "onCreate");
|
|
|
+ timeTickReceiver = new TimeTickReceiver();
|
|
|
+ // 监听分钟广播
|
|
|
+ registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public int onStartCommand(Intent intent, int flags, int startId) {
|
|
|
+ LogUtils.d(getClass().getName(), "onStartCommand");
|
|
|
+ Notification notification = createNotification();
|
|
|
+ startForeground(1, notification);
|
|
|
+ return START_REDELIVER_INTENT;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onTaskRemoved(Intent rootIntent) {
|
|
|
+ super.onTaskRemoved(rootIntent);
|
|
|
+ LogUtils.d(getClass().getName(), "onTaskRemoved");
|
|
|
+ stopSelf();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onDestroy() {
|
|
|
+ super.onDestroy();
|
|
|
+ if (null != timeTickReceiver) {
|
|
|
+ unregisterReceiver(timeTickReceiver);
|
|
|
+ timeTickReceiver = null;
|
|
|
+ }
|
|
|
+ LogUtils.d(getClass().getName(), "onDestroy");
|
|
|
+ }
|
|
|
+
|
|
|
+ private void createNotificationChannel() {
|
|
|
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
|
+ int importance = NotificationManager.IMPORTANCE_DEFAULT;
|
|
|
+ NotificationChannel channel = new NotificationChannel("task", "task", importance);
|
|
|
+ NotificationManager notificationManager = getSystemService(NotificationManager.class);
|
|
|
+ notificationManager.createNotificationChannel(channel);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Notification createNotification() {
|
|
|
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "task")
|
|
|
+ .setContentTitle("Task")
|
|
|
+ .setContentText("Task is running")
|
|
|
+ .setSmallIcon(R.mipmap.ic_launcher)
|
|
|
+ .setContentIntent(null)
|
|
|
+ .setSilent(true)
|
|
|
+ .setPriority(NotificationCompat.PRIORITY_DEFAULT);
|
|
|
+ return builder.build();
|
|
|
+ }
|
|
|
+}
|