android创建通知栏(java版)

 

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 应用程序
 */
public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    /**
     * 创建通知栏渠道
     */
    private void createNotificationChannel() {
        /**
         * 在API 26+ 创建NotificationChannel
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            List<HashMap<String, String>> list = new ArrayList<>();
            HashMap<String, String> hashMap;
            hashMap = new HashMap<>();
            hashMap.put("name", "聊天");
            hashMap.put("description", "聊天消息通知");
            hashMap.put("channel", Constant.notifyChannelChat);
            list.add(hashMap);

            hashMap = new HashMap<>();
            hashMap.put("name", "订阅");
            hashMap.put("description", "订阅消息通知");
            hashMap.put("channel", Constant.notifyChannelSubscription);
            list.add(hashMap);

            hashMap = new HashMap<>();
            hashMap.put("name", "推荐");
            hashMap.put("description", "推荐消息通知");
            hashMap.put("channel", Constant.notifyChannelRecommend);
            list.add(hashMap);

            hashMap = new HashMap<>();
            hashMap.put("name", "新闻");
            hashMap.put("description", "新聞消息通知");
            hashMap.put("channel", Constant.notifyChannelNews);
            list.add(hashMap);

            hashMap = new HashMap<>();
            hashMap.put("name", "其他");
            hashMap.put("description", "其他消息通知");
            hashMap.put("channel", Constant.notifyChannelOther);
            list.add(hashMap);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> map = list.get(i);
                String textName = MapUtil.getMapValue(map, "name");
                String textDescription = MapUtil.getMapValue(map, "description");
                String textChannel = MapUtil.getMapValue(map, "channel");
                NotificationChannel channelOther = new NotificationChannel(textChannel, textName, NotificationManager.IMPORTANCE_DEFAULT);
                channelOther.setDescription(textDescription);
                notificationManager.createNotificationChannel(channelOther);
            }
        }
    }

}

 

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.util.HashMap;
import java.util.Map;

/**
 * 主界面
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_notification).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<>();
                map.put("channel", "1");
                map.put("title", "张三");
                map.put("content", "你最近还好吗");
                map.put("big_text", "-------------------------------------------------------------");
                // https://developer.android.com/training/notify-user/build-notification?hl=zh-cn#java
                NotificationUtil.sendNotification(MainActivity.this, map);
            }
        });
    }

}

 

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import java.util.Map;
import java.util.Random;

/**
 * 通知栏工具类
 */
public class NotificationUtil {

    public static void sendNotification(Context context, Map<String, String> map) {
        if (context != null && map != null) {
            String channel = MapUtil.getMapValue(map, "channel", "0");
            String channelId = Constant.notifyChannelOther;
            switch (channel) {
                case "0":
                    channelId = Constant.notifyChannelOther;
                    break;
                case "1":
                    channelId = Constant.notifyChannelChat;
                    break;
                case "2":
                    channelId = Constant.notifyChannelNews;
                    break;
                case "3":
                    channelId = Constant.notifyChannelRecommend;
                    break;
                case "4":
                    channelId = Constant.notifyChannelSubscription;
                    break;
            }
            String title = MapUtil.getMapValue(map, "title");
            String content = MapUtil.getMapValue(map, "content");
            // 设置通知内容,构造函数要求您提供通道ID。这是与Android 8.0(API级别26)及更高版本兼容所必需的,但旧版本会忽略这一点
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                    .setSmallIcon(R.drawable.notification_icon)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            String bigText = MapUtil.getMapValue(map, "big_text");
            // 如果bigText的值不为空
            if (!TextUtils.isEmpty(bigText)) {
                // 如果您希望通知更长,可以通过添加样式模板来启用可扩展通知
                mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText));
            }

            // 为应用中的活动创建明确的意图
            Intent intent = new Intent(context, NotificationClickReceiver.class);
            intent.setAction(NotificationClickReceiver.noticeClick);
            intent.putExtras(MapUtil.getBundle(map));
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, new Random().nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(pendingIntent);

            // 显示通知,注意:从Android 8.1(API级别27)开始,应用程序无法每秒发出超过一次的通知。
            // 如果您的应用在一秒钟内发布了多个通知,则它们都会按预期显示,但每秒只有第一个通知发出声音
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            notificationManager.notify(new Random().nextInt(1000), mBuilder.build());
        }
    }

}

 

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

/**
 * 监听通知栏点击事件
 */
public class NotificationClickReceiver extends BroadcastReceiver {

    public final static String noticeClick = "android.intent.action.noticeClick";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (context != null && intent != null && intent.getAction() != null && intent.getAction().equals(noticeClick)) {
            // 通知栏被点击
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Toast.makeText(context, "收到消息", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

 

import android.os.Bundle;
import android.text.TextUtils;
import java.util.Map;

/**
 * Map工具类
 */
public class MapUtil {

    /**
     * 根据map的key取map的值
     */
    public static String getMapValue(Map<String, String> map, String key) {
        if (map != null && !TextUtils.isEmpty(key) && map.containsKey(key)) {
            return map.get(key);
        } else {
            return "";
        }
    }

    /**
     * 根据map的key取map的值,当map的值为空时取传过来的默认值
     */
    public static String getMapValue(Map<String, String> map, String key, String defaultValue) {
        if (map != null && !TextUtils.isEmpty(key) && map.containsKey(key)) {
            String value = map.get(key);
            if (value != null) {
                return value;
            } else {
                return defaultValue;
            }
        } else {
            return defaultValue;
        }
    }

    /**
     * 把map转换成bundle
     */
    public static Bundle getBundle(Map<String, String> map) {
        Bundle bundle = new Bundle();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                if (!TextUtils.isEmpty(key)) {
                    bundle.putString(key, entry.getValue());
                }
            }
        }
        return bundle;
    }

}

 

/**
 * 常量类
 */
public class Constant {

    // 通知渠道ID:聊天
    public final static String notifyChannelChat = "chat";
    // 通知渠道ID:订阅
    public final static String notifyChannelSubscription = "subscription";
    // 通知渠道ID:推荐
    public final static String notifyChannelRecommend = "recommend";
    // 通知渠道ID:新闻
    public final static String notifyChannelNews = "news";
    // 通知渠道ID:其他
    public final static String notifyChannelOther = "other";

}

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="">

    <application
        android:name=".BaseApplication">

        <receiver android:name=".NotificationClickReceiver">
            <intent-filter>
                <action android:name="android.intent.action.noticeClick" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

 点击查看kotlin版 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值