Android Foreground Service

為了防止后臺服務(wù)被系統(tǒng)干掉,我們需要將服務(wù)提升為前臺服務(wù)。

示例代碼:

需要在AndroidManifest 添加 前臺服務(wù)的權(quán)限 :
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

FOREGROUND_SERVICE
Added in API level 28 Android 9.0
public static final String FOREGROUND_SERVICE
Allows a regular application to use Service.startForeground.
Protection level: normal
Constant Value: android.permission.FOREGROUND_SERVICE
public class SampleService extends Service {

    public static final String CHANNEL_ID = "com.github.103style.SampleService";
    public static final String CHANNEL_NAME = "com.github.103style";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerNotificationChannel();
        int notifyId = (int) System.currentTimeMillis();
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
        mBuilder
                //必須要有
                .setSmallIcon(R.mipmap.ic_launcher)
                //可選
                //.setSound(null)
                //.setVibrate(null)
                //...
        ;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mBuilder.setContentTitle(getResources().getString(R.string.app_name));
        }
        startForeground(notifyId, mBuilder.build());
    }

    /**
     * 注冊通知通道
     */
    private void registerNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
            if (notificationChannel == null) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                        CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                //是否在桌面icon右上角展示小紅點
                channel.enableLights(true);
                //小紅點顏色
                channel.setLightColor(Color.RED);
                //通知顯示
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                //是否在久按桌面圖標(biāo)時顯示此渠道的通知
                //channel.setShowBadge(true);
                mNotificationManager.createNotificationChannel(channel);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容