有些小伙伴会遇到这样的问题:如果想让一个服务在后台长期的运行下去,而且在系统资源不足的情况下不会被系统kill掉,怎么办?这个时候上网google之后会发现,有个叫“前台服务”的东东,貌似很强大,无论怎样都会常驻系统内存。但是,都会发现,在高版本的Android版本中,前台服务一旦运行,就会默认在通知栏显示运行状态,无法手动去除。
有什么好的办法可以让其运行但又不会显示在通知栏的办法吗?
答案肯定有,在我动手实践后,发现了一个绝对有效的办法(也查阅过之前网友的做法,但是好像有漏洞,我这里说明的更详细,会考虑到各个版本,需要的小伙伴直接copy就可以用了),废话不多说,盖茨,上代码!
工程目录:
这里,前台服务名称为ForegroundService,协助我们去掉通知栏的Service为HelpService,入口为MainActivity
package com.example.foregroundservice;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startForeground(View view) {
Intent intent = new Intent(this, ForegroundService.class);
startService(intent);
}
}
ForegroundService部分:
package com.example.foregroundservice;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import an