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

1.权限:

<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;


/**
 * 别忘记询问用户开发锁屏时显示权限
 * <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);
        //创建一个跳转到活动页面的意图
        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<ChargeStatusBean> result= gson.fromJson(msg,new TypeToken<WebSocketResult<ChargeStatusBean>>() {}.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

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

4.调用

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">
    <!--在小米上自己定义的背景和圆角无效果-->
<!--    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="预计充满还需25分钟"/>
    </RelativeLayout>
</LinearLayout>

6.效果图


Screenshot_2022-10-28-10-27-31-617_lockscreen.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容