本帖最后由 采集的小蜜蜂 于 2021-6-16 18:42 编辑
用的小米6,安卓9,
目标:点击按钮开启AlarmService.class,
在服务中制定一个10秒后的AlarmManager定时任务,
定时到了后会执行新的Service,pendingintent(NotificationService.class)
在这个服务中会把通知的一些相关内容一下。
[Java] 纯文本查看 复制代码 public class AlarmService extends Service {
public AlarmManager alarmManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intentservice=new Intent(this,NotificationService.class);
PendingIntent pendingIntent=PendingIntent.getService(this,0,intentservice,0);
alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, finalchuo, pendingIntent);
return START_STICKY;
}
[Java] 纯文本查看 复制代码 package com.ykd.bed.service;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.ykd.bed.R;
import com.ykd.bed.activity.AutoSearchActivity;
import java.util.Calendar;
import static com.ykd.bed.activity.WakeUpActivity.finalchuo;
public class NotificationService extends Service {
private NotificationChannel notificationChannel = null;
public AlarmManager alarmManager;
private PendingIntent pendingIntent;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, finalchuo, pendingIntent);
Intent intentSevice=new Intent(this,NotificationService.class);
pendingIntent=PendingIntent.getService(this,0,intentSevice,0);
NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel("1", "channel_name", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
Notification notification=new NotificationCompat.Builder(this,"1")
.setContentTitle("唤醒闹钟")
.setContentText("滑动关闭闹钟")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.app_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon))
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.build();
notificationManager.notify(1,notification);
return START_STICKY;
}
}
问题:
使用APP或使APP切换到后台以后(直接返回到桌面,后台不关闭),都能在状态栏成功接收到通知。
但凡后台退出APP后,如果不把APP的自启动和后台限制设置为无限制,就永远收不到通知
我感觉在我后台划掉APP后,服务也被杀死了,我使用的startService,不是bindservice。
另外我想问一下怎么让我的通知不进入到小米的不重要通知之内。 |