设置点击事件 , 点击启动服务
Intent i = new Intent(context, LongRunningService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(i);
} else {
context.startService(i);
}
服务类
class LongRunningService extends Service {
private static final int NOTICE_FG_ID = 2;
private Notification notification;
private Context context;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
context = this;
//开启前台服务
startForeground(NOTICE_FG_ID, getNotification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//业务逻辑
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println( <=网络 ----后台保活----- wifi=>");
}
}, 1000, 1000 * 10);
//业务逻辑结束
return START_STICKY;
}
public Notification getNotification() {
//1:获取系统提供的通知管理服务
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
//2:如果是8以上的系统,则新建一个消息通道,传一个channelId
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "测试";//消息通道的id,以后可以通过该id找到该消息通道
String channelName = "测试通知";//消息通道的name
// 通知的优先级,作用就是优先级的不同。可以导致消息出现的形式不一样。
// HIGH是会震动并且出现在屏幕的上方。设置优先级为low或者min时。来通知时都不会震动,且不会直接出现在屏幕上方
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Intent intent = new Intent(this, ServiceLifeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("我测试")
.setContentText("请不要关闭我!")
// .setContentText(TimeUtil.getNowMDHMSTime())
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
Notification notification = builder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT; // 设置常驻,不能滑动取消
return notification;
}
}
注册service
动态或静态注册