1+ package com .zfdang .touchhelper ;
2+
3+ import android .app .Notification ;
4+ import android .app .NotificationChannel ;
5+ import android .app .NotificationManager ;
6+ import android .app .Service ;
7+ import android .content .Context ;
8+ import android .content .Intent ;
9+ import android .os .Build ;
10+ import android .os .IBinder ;
11+ import android .util .Log ;
12+
13+ public class ForeGroundService extends Service {
14+ private static final String TAG = ForeGroundService .class .getSimpleName ();
15+ NotificationManager notificationManager ;
16+ String notificationId = "touch" ;
17+ String notificationName = "常驻服务" ;
18+
19+ private void startForegroundService () {
20+ notificationManager = (NotificationManager ) getSystemService (Context .NOTIFICATION_SERVICE );
21+ //创建 NotificationChannel
22+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
23+ NotificationChannel channel = new NotificationChannel (notificationId , notificationName , NotificationManager .IMPORTANCE_HIGH );
24+ notificationManager .createNotificationChannel (channel );
25+ }
26+ startForeground (1 , getNotification ());
27+
28+ }
29+
30+ private Notification getNotification () {
31+ Notification .Builder builder = new Notification .Builder (this )
32+ .setSmallIcon (R .drawable .ic_touch_helper_icon )
33+ .setContentTitle (getString (R .string .app_name ))
34+ .setContentText (getString (R .string .app_name ) + "正在运行..." );
35+
36+ //设置Notification的ChannelID,否则不能正常显示
37+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
38+ builder .setChannelId (notificationId );
39+ }
40+ Notification notification = builder .build ();
41+ return notification ;
42+
43+ }
44+
45+ @ Override
46+ public void onCreate () {
47+ super .onCreate ();
48+ startForegroundService ();
49+ Log .d (TAG , "onCreate()" );
50+ }
51+
52+
53+ @ Override
54+ public int onStartCommand (Intent intent , int flags , int startId ) {
55+ Log .d (TAG , "onStartCommand()" );
56+ return super .onStartCommand (intent , flags , startId );
57+ }
58+
59+
60+ @ Override
61+ public void onDestroy () {
62+ Log .d (TAG , "onDestroy()" );
63+ stopForeground (true );// 停止前台服务--参数:表示是否移除之前的通知
64+ super .onDestroy ();
65+ }
66+
67+ @ Override
68+ public IBinder onBind (Intent intent ) {
69+ Log .d (TAG , "onBind()" );
70+ // TODO: Return the communication channel to the service.
71+ throw new UnsupportedOperationException ("Not yet implemented" );
72+ }
73+ }
0 commit comments