android后台进程常驻,android 后台常驻,不会被kill

  • Post author:
  • Post category:其他


第一步:

import android.app.Notification;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.IBinder;

import android.util.Log;

import com.unopenbox.client.MainActivity;

import com.unopenbox.client.R;

import com.unopenbox.client.bean.MyResponse1;

import com.unopenbox.client.network.OkHttpClientManager;

import org.json.JSONException;

import okhttp3.Request;

import static android.app.Notification.PRIORITY_MAX;

/**

* Created by Administrator on 2018/9/13 0013.

*/

public class BackGroundService extends Service {

Notification notification;

private Context mContext;

private MediaPlayer bgmediaPlayer;

private boolean isrun = true;

public BackGroundService() {

}

@Override

public int onStartCo妹妹and(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.drawable.icon_bg)

.setWhen(System.currentTimeMillis())

.setTicker(“GPS测试”)

.setContentTitle(“GPS测试标题”)

.setContentText(“GPS测试内容”)

.setOngoing(true)

.setPriority(PRIORITY_MAX)

.setContentIntent(pendingIntent)

.setAutoCancel(false)

.build();

/*应用startForeground,要是id为0,辣么notification将不会显示*/

startForeground(100, notification);

//2.开启线程(大概必要按时操作的工作)

new Thread() {

@Override

public void run() {

super.run();

while (isrun) {

//你必要实行的使命

try {

Thread.sleep(10000);

} catch (InterruptedException es) {

es.printStackTrace();

}

OkHttpClientManager.postAsyn(OkHttpClientManager.ip + “item/returnDeadline”, new OkHttpClientManager.ResultCallback() {

@Override

public void onError(Request request, Exception e) {

Log.e(“=============”, “1”);

}

@Override

public void onResponse(MyResponse1 response) throws JSONException {

}

}, new OkHttpClientManager.Param(“”, “”));

}

//举行本人的操作

}

}.start();

//3.非常环节的神来之笔,也是非常谋利的动作,没办法要骗过CPU

//这即是播放音乐类APP不被杀的做法,本人找个无声MP3放进来轮回播放

if (bgmediaPlayer == null) {

bgmediaPlayer = MediaPlayer.create(this, R.raw.silent);

bgmediaPlayer.setLooping(true);

bgmediaPlayer.start();

}

return START_STICKY;

}

@Override

public IBinder onBind(Intent intent) {

throw new UnsupportedOperationException(“Not yet implemented”);

}

@Override

public void onDestroy() {

isrun = false;

stopForeground(true);

bgmediaPlayer.release();

stopSelf();

super.onDestroy();

}

}

第二步:

AndroidManifest中进入

android:name=”.test.BackGroundService”

android:enabled=”true”

android:exported=”true” />

第三步:

在你必要挪用的页面挪用

Intent forgroundService = new Intent(this,BackGroundService.class);

startService(forgroundService);

结束,我这边做的测试是没问题  能够跑一晚上 没被kill