让服务以notification的形式,显示在前台,不容易被杀死

只需在Service的inCreate里面,构建notification,不是用NotificationManager启动,而是用startForeground来启动即可

构造pengdingIntent使前台可以打开原来的activity

 

Service代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
public class MyService extends Service {
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        Intent intent = new Intent(this,MainActivity.class);
 
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
 
        Notification notify = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏中的小图片,尺寸一般建议在24×24,这个图片同样也是在下拉状态栏中所显示,如果在那里需要更换更大的图片,可以使用setLargeIcon(Bitmap
                // icon)
                .setTicker("Service")// 设置在status
 
                // bar上显示的提示文字
                .setContentTitle("Notification Title")// 设置在下拉status
                // bar后Activity,本例子中的NotififyMessage的TextView中显示的标题
                .setContentText("This is Service")// TextView中显示的详细内容
 
                .setContentIntent(pendingIntent) // 关联PendingIntent
                .setNumber(1// 在TextView的右方显示的数字,可放大图片看,在最右侧。这个number同时也起到一个***的左右,如果多个触发多个通知(同一ID),可以指定显示哪一个。
                .build();
 
        startForeground(1, notify);
    }

 

MainActivity:

1
2
3
4
5
6
7
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this,MyService.class);
                    startService(intent);
            }
        });

 

Service前台服务

相关文章: