zl程序教程

您现在的位置是:首页 >  APP

当前栏目

[android] notification入门

2023-02-18 15:47:26 时间

通知栏,对话框,Toast是我们接触的三个提示框,通知栏是在系统的应用com.adnroid.systemui当中的

 

接触的几个MangergetSystemService()方法得到的,参数:

ACTIVITY_SERVICELAYOUT_INFLATER_SERVICTELEPHONY_SERVICE

 

获取NotificationManager对象,通过getSystemService()方法,参数:NOTIFICATION_SERVICE

调用NotificationManager对象的notify()方法,发送通知,参数:id0Notification对象

获取Builder对象,通过new Notification.Builder()

调用Builder对象的setContentTitle() setContentText() setSmallIcon()  setLargeIcon()

setLargeIcon的参数:Bitmap对象,BitmapFactory.decodeResource(),参数:getResoure(),资源id

调用Builder对象的build()方法,得到Notification对象

此时会报一些错误,最低兼容版本是11,我们直接加一个注释屏蔽掉错误”NewApi”

 

在低版本的手机上,上面的代码会出错

获取Notification对象,通过new出来,参数:资源id,文本,时间

调用Notification对象的setLastEventInfo()方法,设置最新消息,参数:上下文,文本,PendingIntent对象

 

设置Notification对象的flags属性为Notification.FLAG_AUTO_CANCEL 自动关闭

PendingIntent对象,通过PendingIntentgetActivity()方法,获取到PendingIntent对象

6.0 版本移除了Notification.setLatestEventInfo()方法

流氓软件会使用这来弹广告,我们可以进系统应用设置,勾掉显示通知

package com.tsh.tshnotification;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //显示通知栏
    @SuppressLint("NewApi")
    public void click(View v){
        NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder=new Notification.Builder(this);
        Notification notification=builder.setContentTitle("提示")
                .setContentText("我是陶士涵")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .build();
                
        nm.notify(0, notification);
    }
}