import static android.app.Notification.PRIORITY_MAX; /** * Created by tyl * 2019/11/12/012 * Describe: */ public class BackGroundService extends Service { Notification notification; private Context mContext; private static Thread uploadGpsThread; private MediaPlayer bgmediaPlayer; private boolean isrun = true; @Override public int onStartCommand(Intent intent, int flags, int startId) { mContext = this; Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); //1.通知栏占用,不清楚的看官网或者音乐类APP的效果 notification = new Notification.Builder(mContext) .setSmallIcon(R.mipmap.icon_notifacation_log) .setWhen(System.currentTimeMillis()) .setTicker(getResources().getString(R.string.app_name)) .setContentTitle(getResources().getString(R.string.app_name)) .setContentText("正在后台运行") .setOngoing(true) .setPriority(PRIORITY_MAX) .setContentIntent(pendingIntent) .setAutoCancel(false) .build(); /*使用startForeground,如果id为0,那么notification将不会显示*/ startForeground(2479, buildNotification()); //2.最关键的神来之笔,也是最投机的动作,没办法要骗过CPU //这就是播放音乐类APP不被杀的做法,自己找个无声MP3放进来循环播放 if(bgmediaPlayer == null){ bgmediaPlayer = MediaPlayer.create(this,R.raw.slient); bgmediaPlayer.setLooping(true); bgmediaPlayer.start(); } return START_STICKY; }
@Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); }