android自定义通知栏_推送图片

本文介绍了一种自定义推送通知的方法,重点在于根据不同的手机通知栏背景颜色动态调整通知文字颜色,确保信息清晰可见。提供了具体的布局代码及一个工具类用于判断系统通知栏背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

系统默认的推送能解决大多数需求,自定义推送通知栏,主要是推送图片。不同手机通知栏背景颜色不一样,就要动态改变通知文字的颜色,不然会出现文字显示不出来现象。如华为手机通知栏背景是黑色的,就要把文字设置为白色,OPPO手机通知栏背景是灰色的,就要把文字设置为白色。我已经写了工具类,判断系统通知栏背景颜色,直接拷贝用酒匂。

本博客不啰嗦,直接上代码,喜欢就关注一下,谢谢支持

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:paddingLeft="5dp"
        >
        <ImageView
            android:id="@+id/iconImageView"
            android:layout_width="15dp"
            android:layout_height="20dp"
            android:layout_marginLeft="5dp"
            />
        <TextView
            android:id="@+id/appNameTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:text="玉委会会刊"/>
    </LinearLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginRight="60dp"
            android:paddingLeft="5dp"
            android:layout_gravity="center_vertical">
            <TextView
                android:id="@+id/title_TextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:ellipsize="end"
                android:text="标题"
                />
            <TextView
                android:id="@+id/content_TextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:ellipsize="end"
                android:text="我是内容"
                />
        </LinearLayout>
        <ImageView
            android:id="@+id/ImageView"
            android:gravity="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@mipmap/ic_launcher"/>
    </RelativeLayout>
</LinearLayout>
代码

//判断系统通知栏背景颜色
        boolean darkNotiFicationBar = NotificationsUtils.isDarkNotiFicationBar(this);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.baidu_message);
        //设置通知栏背景
        remoteViews.setTextColor(R.id.appNameTextView, darkNotiFicationBar == true?Color.WHITE:Color.BLACK);
        remoteViews.setTextColor(R.id.title_TextView,  darkNotiFicationBar == true?Color.WHITE:Color.BLACK);
        remoteViews.setTextColor(R.id.content_TextView,  darkNotiFicationBar == true?Color.WHITE:Color.BLACK);
        //设置文字大小
        remoteViews.setTextViewTextSize(R.id.title_TextView, COMPLEX_UNIT_SP ,16);
        remoteViews.setTextViewTextSize(R.id.content_TextView, COMPLEX_UNIT_SP ,14);
        //添加内容
        remoteViews.setImageViewResource(R.id.iconImageView, R.drawable.icon);
        remoteViews.setTextViewText(R.id.appNameTextView, "紫禁城" );
        remoteViews.setTextViewText(R.id.title_TextView, "紫禁城放假了" );
        remoteViews.setTextViewText(R.id.content_TextView, "紫禁城免费了" );
        //实例化通知栏构造器。
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //系统收到通知时,通知栏上面显示的文字。
        mBuilder.setTicker("通知栏上面显示的文字");
        mBuilder.setContent(remoteViews);//获得Notification定高
        mBuilder.setCustomBigContentView(remoteViews);
       //显示在通知栏上的小图标
        mBuilder.setSmallIcon(R.drawable.icon);
        //设置大图标,即通知条上左侧的图片(如果只设置了小图标,则此处会显示小图标)
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
        //添加声音
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        Intent intent = new Intent(this, MainActivity.class);//点击通知,进入应用
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mBuilder.setContentIntent(pendingIntent);//点击通知栏后的意图
        mBuilder.setAutoCancel(true);//设置这个标志当用户单击面板就可以让通知将自动取消
        //设置为不可清除模式
//        mBuilder.setOngoing(true);
        //显示通知,id必须不重复,否则新的通知会覆盖旧的通知(利用这一特性,可以对通知进行更新)
        NotificationManager mm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = mBuilder.build();
        mm.notify(1, notification);
        Picasso.with(this).load( message )//message 就是图片链接地址
                .resize(200,200)
                .centerCrop()
                .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                .into(remoteViews, R.id.ImageView, 1, notification);

判断系统通知栏颜色工具类

/**
 * 通知栏的帮助类,提供查询手机是否禁止通知栏,判断通知栏背景颜色
 * Created by dengqu on 2016/12/12.
 */
public class NotificationsUtils {
    private final static String TAG = NotificationsUtils.class.getSimpleName();
    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
    private static final double COLOR_THRESHOLD = 180.0;
    private static int titleColor;
    /**
     * 判断应用通知栏是否开启权限
     *
     * @param context
     * @return
     */
//    public static boolean isNotificationEnabled(Context context) {
//        try {
//            if (AndroidConfig.getAndroidVersion() >= Build.VERSION_CODES.KITKAT) {
//                AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
//                ApplicationInfo appInfo = context.getApplicationInfo();
//                String pkg = context.getApplicationContext().getPackageName();
//                int uid = appInfo.uid;
//                Class appOpsClass = null;
//                appOpsClass = Class.forName(AppOpsManager.class.getName());
//                Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
//                Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
//                int value = (int) opPostNotificationValue.get(Integer.class);
//                return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
//            }
//        } catch (Exception e) {
//           // XLLog.e(TAG, e);
//        }
//        return true;
//    }
    /**
     * 判断通知栏背景颜色,现在手机通知栏大部分不是白色就是黑色背景
     *
     * @param context
     * @return
     */
    public static boolean isDarkNotiFicationBar(Context context) {
        return !isColorSimilar(Color.BLACK, getNotificationColor(context));
    }
    private static int getNotificationColor(Context context) {
        if (context instanceof AppCompatActivity) {
            return getNotificationColorCompat(context);
        } else {
            return getNotificationColorInternal(context);
        }
    }
    private static boolean isColorSimilar(int baseColor, int color) {
        int simpleBaseColor = baseColor | 0xff000000;
        int simpleColor = color | 0xff000000;
        int baseRed = Color.red(simpleBaseColor) - Color.red(simpleColor);
        int baseGreen = Color.green(simpleBaseColor) - Color.green(simpleColor);
        int baseBlue = Color.blue(simpleBaseColor) - Color.blue(simpleColor);
        double value = Math.sqrt(baseRed * baseRed + baseGreen * baseGreen + baseBlue * baseBlue);
        if (value < COLOR_THRESHOLD) {
            return true;
        }
        return false;
    }
    private static int getNotificationColorInternal(Context context) {
        final String DUMMY_TITLE = "DUMMY_TITLE";
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentText(DUMMY_TITLE);
        Notification notification = builder.build();
        RemoteViews contentView = notification.contentView;
        if ( contentView == null ) {
            return 0;
        }
        ViewGroup notificationRoot = (ViewGroup) contentView.apply(context, new FrameLayout(context));
        final TextView titleView = (TextView) notificationRoot.findViewById(android.R.id.title);
        if (titleView == null) {
            iteratoryView(notificationRoot, new Filter() {
                @Override
                public void filter(View view) {
                    if (view instanceof TextView) {
                        TextView textView = (TextView) view;
                        if (DUMMY_TITLE.equals(textView.getText().toString())) {
                            titleColor = textView.getCurrentTextColor();
                        }
                    }
                }
            });
            return titleColor;
        } else {
            return titleView.getCurrentTextColor();
        }
    }
    private static int getNotificationColorCompat(Context context) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Notification notification = builder.build();
        RemoteViews contentView = notification.contentView;
        if ( contentView == null ) {
           return 0;
        }
        int layoutId = contentView.getLayoutId();
        ViewGroup notificationRoot = (ViewGroup) LayoutInflater.from(context).inflate(layoutId, null);
        final TextView titleView = (TextView) notificationRoot.findViewById(android.R.id.title);
        if (titleView == null) {
            final List<TextView> textViews = new ArrayList<>();
            iteratoryView(notificationRoot, new Filter() {
                @Override
                public void filter(View view) {
                    textViews.add((TextView) view);
                }
            });
            float minTextSize = Integer.MIN_VALUE;
            int index = 0;
            for (int i = 0, j = textViews.size(); i < j; i++) {
                float currentSize = textViews.get(i).getTextSize();
                if (currentSize > minTextSize) {
                    minTextSize = currentSize;
                    index = i;
                }
            }
            return textViews.get(index).getCurrentTextColor();
        } else {
            return titleView.getCurrentTextColor();
        }
    }
    private static void iteratoryView(View view, Filter filter) {
        if (view == null || filter == null) {
            return;
        }
        filter.filter(view);
        if (view instanceof ViewGroup) {
            ViewGroup container = (ViewGroup) view;
            for (int i = 0, j = container.getChildCount(); i < j; i++) {
                View child = container.getChildAt(i);
                iteratoryView(child, filter);
            }
        }
    }
    private interface Filter {
        void filter(View view);
    }
}





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值