适配安卓8.0以上推送通知栏
1.推送弹出通知栏
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 创建
NotificationChannel channel = new NotificationChannel(id, content, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.setShowBadge(true);
manager.createNotificationChannel(channel);
}
//自定义打开的界面
Intent resultIntent = new Intent(context.getApplicationContext(), MainActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle(title)
.setContentText(content)
.setContentIntent(contentIntent)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_logo))
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_logo)
.setColor(Color.BLUE);
manager.notify(1, mBuilder.build());
2.在Service中弹出通知栏
ndroid系统8.0及以上,开启Service必须使用startForegroundService(Intent intent)方法,对应的Service则必须设置startForeground(int id, Notification notification),因而我们必须创建一个通知,这样在服务运行当中,会一直显示一条“xx正在运行”类似的通知。
在8.0以上系统中开启startService之后5秒内必须开启startForeground(1, notification);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification notification = new Notification.Builder(getApplicationContext(),createNotificationChannel()).build();
startForeground(1, notification);
}
替代方案:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CowboyJobService extends JobService {
@Override
public boolean onStartJob(JobParameters jobParameters) {
//此处进行自定义的任务
return false;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}
//开启JobService服务:CowboyJobService.class为上边创建的JobService
public static void startPollingService(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(context, CowboyJobService.class));
builder.setMinimumLatency(0)
.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setPeriodic(JobInfo.getMinPeriodMillis(), JobInfo.getMinFlexMillis());
} else {
builder.setPeriodic(TimeUnit.MINUTES.toMillis(5));
}
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(builder.build());
}
} else {
//系统5.0以下的可继续使用Service
}
}
网友评论