android 后台常驻,不会被系统kill

第一步:

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 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.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<MyResponse1>() {
                        @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中加入

<service
    android:name=".test.BackGroundService"
    android:enabled="true"
    android:exported="true" />

第三步:

在你需要调用的页面调用

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

startService(forgroundService);

结束,我这边做的测试是没问题  可以跑一夜 没被kill

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值