公司有个项目,需要开个服务在后台运行, 并不容易让系统清掉,也能在通知栏有显示该服务正在运行。
主要service 代码如下: 主要是在service onCreate的时候,要使用一个notification 常驻在通知栏
@Override
public void onCreate() {
super.onCreate();
foregroundRun();
}
/**
* 使服务更好的运行在后台, 不被销毁(手机内存低时不优先销毁)
*/
private void foregroundRun() {
PendingIntent p_intent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("ina-ina")
.setContentTitle("Ina_Service")
.setContentText("Service is Running!")
.setContentIntent(p_intent)
.build();
startForeground(0x1989, notification); // notification ID: 0x1982, you can name it as you will.
}