Android保活

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

1.準備一個前臺BackGroundService

package com.guoshikeji.xiaoxiangDriver.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
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 com.guoshikeji.xiaoxiangDriver.MainActivity;
import com.guoshikeji.xiaoxiangDriver.R;

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放進來循環(huán)播放
        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");
    }

    @Override
    public void onDestroy() {
        isrun = false;
        stopForeground(true);
        bgmediaPlayer.release();
        stopSelf();
        super.onDestroy();
    }

    private NotificationManager notificationManager;
    private boolean isCreateChannel = false;
    @SuppressLint("NewApi")
    private Notification buildNotification() {
        Notification.Builder builder = null;
        Notification notification = null;

        if (android.os.Build.VERSION.SDK_INT >= 26) {
            if (null == notificationManager) {
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        "BackgroundLocation", NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(false);//是否在桌面icon右上角展示小圓點
                notificationChannel.setShowBadge(true); //是否在久按桌面圖標時顯示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.icon_notifacation_log)
                .setColor(getResources().getColor(R.color.main_color))
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("正在后臺運行")
                .setWhen(System.currentTimeMillis());
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }
}

2. 在對應的activity里顯示開啟service

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

3. 在AndroidManifest.xml文件里申明service

<service
    android:name=".BackGroundService"
    android:enabled="true"
    android:exported="true" />
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容