前台服务
让服务以notification的形式,显示在前台,不容易被杀死
只需在Service的inCreate里面,构建notification,不是用NotificationManager启动,而是用startForeground来启动即可
构造pengdingIntent使前台可以打开原来的activity
Service代码:
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 notify2 = 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,notify2);
Log.d("TAG","onCreate");
}
}
MainActivity:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,myService.class);
startService(intent);
}
});


浙公网安备 33010602011771号