android使用前臺(tái)服務(wù)和notification實(shí)現(xiàn)鎖屏通知

1.權(quán)限:

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

2.service代碼:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


/**
 * 別忘記詢問(wèn)用戶開(kāi)發(fā)鎖屏?xí)r顯示權(quán)限
 * <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
 */
public class ChargeService extends Service {
    private int NOTIFICATION_ID=100;
    @Override
    public void onCreate() {
        super.onCreate();
        //startForeground(200,getNotification("xxx","sss","111"));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(NOTIFICATION_ID,getNotification("111"));
        //return START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }

    private NotificationCompat.Builder builder;
    private Notification getNotification(String channel_id) {

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //創(chuàng)建一個(gè)跳轉(zhuǎn)到活動(dòng)頁(yè)面的意圖
        Intent clickIntent = new Intent(this, ChargingActivity.class);
        clickIntent.putExtra("connectorId", ChargingPileManager.INSTANCE.getChargingOrder().getConnectorId());
        clickIntent.putExtra("operatorId", ChargingPileManager.INSTANCE.getChargingOrder().getOperatorId());
        clickIntent.putExtra("qrCode", "3");
        clickIntent.putExtra("shoppingId", ChargingPileManager.INSTANCE.getChargingOrder().getShoppingId());
        clickIntent.putExtra("startChargeSeq", ChargingPileManager.INSTANCE.getChargingOrder().getStartChargeSeq());
        clickIntent.putExtra("chargingStates", ChargingPileManager.INSTANCE.getChargingOrder().getChargeStatus().toString());
        //clickIntent.putExtra("flag", count);
        //創(chuàng)建一個(gè)用于頁(yè)面跳轉(zhuǎn)的延遲意圖A
        PendingIntent contentIntent = PendingIntent.getActivity(this, 100, clickIntent
                , PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            //Android8.0開(kāi)始必須給每個(gè)通知分配對(duì)應(yīng)的渠道
//            builder = new Notification.Builder(this, channel_id);
            //充電提示和充電進(jìn)度兩個(gè)文字串在系統(tǒng)中app通知設(shè)置頁(yè)可以看到  IMPORTANCE_HIGH
            NotificationChannel channel=new NotificationChannel(channel_id,"充電提示",NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);// 所有情況下顯示,包括鎖屏
            channel.setDescription("充電進(jìn)度");
            mNotificationManager.createNotificationChannel(channel);
        }
        //創(chuàng)建一個(gè)通知消息的構(gòu)造器
        builder = new NotificationCompat.Builder(this,channel_id);
        //需要用RemoteViews才能實(shí)現(xiàn)自定義通知ui,注意RemoteViews的第二個(gè)參數(shù)布局根布局不能為ConstraintLayout
        RemoteViews remoteView =new RemoteViews(getPackageName(), R.layout.notify_charge);

        if (ChargingPileManager.INSTANCE.getChargingOrder().getConnectorType()==3){
            remoteView.setViewVisibility(R.id.ll_progress, View.GONE);
        }else {
            remoteView.setViewVisibility(R.id.ll_progress, View.VISIBLE);
        }
        remoteView.setTextViewText(R.id.tv_title, "正在充電中…");
//        remoteView.setTextViewText(R.id.tv_time, "預(yù)計(jì)充滿還需--分鐘");
        remoteView.setTextViewText(R.id.tv_percent, ChargingPileManager.INSTANCE.getChargingOrder().getSoc()+"");

        builder
                .setSmallIcon(R.mipmap.lynkco_ic_launcher)//設(shè)置狀態(tài)欄里的小圖標(biāo)
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
//                .setCustomBigContentView(remoteView)
                .setCustomContentView(remoteView)
                //.setTicker("提示消息來(lái)啦")//設(shè)置狀態(tài)欄里面的提示文本
                //.setWhen(System.currentTimeMillis())//設(shè)置推送時(shí)間,格式為"小時(shí):分鐘"
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(contentIntent)//設(shè)置內(nèi)容的點(diǎn)擊意圖
                .setAutoCancel(true)//設(shè)置是否允許自動(dòng)清除
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)// 設(shè)置該通知優(yōu)先級(jí)
                //.setOngoing(true)
//                .setContent(remoteView)
                //.setColor(Color.RED)//沒(méi)效果
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//設(shè)置通知欄里面的大圖標(biāo)
                //.setContentTitle(title)//設(shè)置通知欄里面的標(biāo)題文本
//                .setContentText("充電")//設(shè)置通知欄里面的內(nèi)容文本
                ;
        WebSocketClient.getInstance().setScreenLockWebSocketCallback(new ScreenLockWebSocketCallback() {
            @Override
            public void callback(String msg, String msgType, Gson gson) {
                Log.e("cwp","service  msg: "+msg +"   msgType:"+msgType);
                if (msgType.equals(MsgType.P_CHARGE_STATUS.name())){//充電中...
                    WebSocketResult<ChargeStatusBean> result= gson.fromJson(msg,new TypeToken<WebSocketResult<ChargeStatusBean>>() {}.getType());
                    if (result.getData()!=null){
                        //充電未完成時(shí)的顯示
                        remoteView.setTextViewText(R.id.tv_title, "正在充電中…");
//                        String[] time= Utils.getLengthOfTime(result.getData().getEndTime(),result.getData().getStartTime());
//                        remoteView.setTextViewText(R.id.tv_time, "已充時(shí)長(zhǎng)"+time[0]+"小時(shí)"+time[1]+"分鐘");
                        int progress=result.getData().getSoc().intValue();
                        remoteView.setTextViewText(R.id.tv_percent, progress+"");
                    }
                    startForeground(NOTIFICATION_ID,builder.build());
                }
//                else if (msgType.equals(MsgType.P_CHARGE_ORDER_INFO.name())){
//                    stopForeground(true);
//                }
            }

            @Override
            public void fail(int code, String msg) {

            }
        });
        //根據(jù)消息構(gòu)造器創(chuàng)建一個(gè)通知對(duì)象
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            Notification notify = builder.build();
//            //mNotificationManager.notify(200, notify);
//            notify.flags = Notification.FLAG_ONGOING_EVENT;
//            return notify;
//        }
        return builder.build();
    }
}


3.注冊(cè)service

<service android:name=".ChargeService"/>

4.調(diào)用

private lateinit var chargeIntent:Intent
findViewById<View>(R.id.tv_start_stake).setOnClickListener {
            chargeIntent=Intent(this, ChargeService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(chargeIntent)
            } else {
                startService(chargeIntent)
            }
        }
override fun onDestroy() {
        super.onDestroy()
        stopService(chargeIntent)
    }

5.RemoteViews的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp_86"
    android:orientation="horizontal">
    <!--在小米上自己定義的背景和圓角無(wú)效果-->
<!--    android:background="@drawable/bg_222222_round_12"-->
    <RelativeLayout
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@mipmap/img_car_charging"/>
        <TextView
            android:id="@+id/tv_percent"
            android:layout_centerVertical="true"
            android:layout_marginStart="@dimen/dp_60"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:textSize="@dimen/sp_18"
            android:text="75%"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:paddingVertical="@dimen/dp_10"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="@dimen/sp_16"
            android:text="正在充電中…"/>
        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:textColor="@color/color_808080"
            android:textSize="@dimen/sp_14"
            android:text="預(yù)計(jì)充滿還需25分鐘"/>
    </RelativeLayout>
</LinearLayout>

6.效果圖


Screenshot_2022-10-28-10-27-31-617_lockscreen.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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