android使用前台服务和notification实现锁屏通知

1.权限:


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;


/**
 * 别忘记询问用户开发锁屏时显示权限
 * 
 */
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);
        //创建一个跳转到活动页面的意图
        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);
        //创建一个用于页面跳转的延迟意图A
        PendingIntent contentIntent = PendingIntent.getActivity(this, 100, clickIntent
                , PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            //Android8.0开始必须给每个通知分配对应的渠道
//            builder = new Notification.Builder(this, channel_id);
            //充电提示和充电进度两个文字串在系统中app通知设置页可以看到  IMPORTANCE_HIGH
            NotificationChannel channel=new NotificationChannel(channel_id,"充电提示",NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);// 所有情况下显示,包括锁屏
            channel.setDescription("充电进度");
            mNotificationManager.createNotificationChannel(channel);
        }
        //创建一个通知消息的构造器
        builder = new NotificationCompat.Builder(this,channel_id);
        //需要用RemoteViews才能实现自定义通知ui,注意RemoteViews的第二个参数布局根布局不能为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, "预计充满还需--分钟");
        remoteView.setTextViewText(R.id.tv_percent, ChargingPileManager.INSTANCE.getChargingOrder().getSoc()+"");

        builder
                .setSmallIcon(R.mipmap.lynkco_ic_launcher)//设置状态栏里的小图标
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
//                .setCustomBigContentView(remoteView)
                .setCustomContentView(remoteView)
                //.setTicker("提示消息来啦")//设置状态栏里面的提示文本
                //.setWhen(System.currentTimeMillis())//设置推送时间,格式为"小时:分钟"
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(contentIntent)//设置内容的点击意图
                .setAutoCancel(true)//设置是否允许自动清除
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)// 设置该通知优先级
                //.setOngoing(true)
//                .setContent(remoteView)
                //.setColor(Color.RED)//没效果
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//设置通知栏里面的大图标
                //.setContentTitle(title)//设置通知栏里面的标题文本
//                .setContentText("充电")//设置通知栏里面的内容文本
                ;
        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 result= gson.fromJson(msg,new TypeToken>() {}.getType());
                    if (result.getData()!=null){
                        //充电未完成时的显示
                        remoteView.setTextViewText(R.id.tv_title, "正在充电中…");
//                        String[] time= Utils.getLengthOfTime(result.getData().getEndTime(),result.getData().getStartTime());
//                        remoteView.setTextViewText(R.id.tv_time, "已充时长"+time[0]+"小时"+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) {

            }
        });
        //根据消息构造器创建一个通知对象
//        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.注册service


4.调用

private lateinit var chargeIntent:Intent
findViewById(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的布局



    

    
        
        
    

    
        
        
    

6.效果图


Screenshot_2022-10-28-10-27-31-617_lockscreen.jpg

你可能感兴趣的:(android使用前台服务和notification实现锁屏通知)