自己的service可继承下面的ServiceCompat类。
public abstract class ServiceCompat extends Service {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//适配安卓8.0
String channelId = getChannelId() + "";
String channelName = getChannelName();
NotificationChannel channel = new NotificationChannel(channelId, channelName,
NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
startForeground(getChannelId(), getNotification());
//
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// stopForeground(true);
// }
// }, 300);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// //适配安卓8.0
// String channelId = getChannelId() + "";
// String channelName = getChannelName();
// NotificationChannel channel = new NotificationChannel(channelId, channelName,
// NotificationManager.IMPORTANCE_MIN);
// NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.createNotificationChannel(channel);
//
// startForeground(getChannelId(), getNotification());
//
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// stopForeground(true);
// }
// }, 300);
// }
return START_STICKY;
}
/**
* Notification channelName
*
*/
protected abstract String getChannelName();
/**
* Notification channelId,must not be 0
*
*/
protected abstract int getChannelId();
/**
* Default content for notification , subclasses can be overwritten and returned
*/
public String getNotificationContent(){
return "";
}
/**
* Displayed notifications, subclasses can be overwritten and returned
*/
public Notification getNotification() {
return createNormalNotification(getNotificationContent());
}
protected Notification createNormalNotification(String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getChannelId() + "");
if (TextUtils.isEmpty(content)) {
return builder.build();
}
builder.setContentTitle(getString(R.string.app_name))
.setContentText(content)
.setWhen(System.currentTimeMillis())
//.setSmallIcon(getSmallIcon())
// .setLargeIcon(getLargeIcon())
.build();
return builder.build();
}
/**
* Large icon for notification , subclasses can be overwritten and returned
*/
// public Bitmap getLargeIcon() {
// return BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// }
/**
* Small icon for notification , subclasses can be overwritten and returned
*/
// // public int getSmallIcon() {
// return R.mipmap.ic_launcher;
// }
public static void startService(Context context, Intent intent){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//适配安卓8.0
context.startForegroundService(intent);
}else{
context.startService(intent);
}
}
}