[android] notification入门

前端之家收集整理的这篇文章主要介绍了[android] notification入门前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

通知栏,对话框,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;
 android.app.Activity;
 android.app.Notification;
 android.app.NotificationManager;
 android.graphics.BitmapFactory;
 android.os.Bundle;
 android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //显示通知
    @SuppressLint("NewApi")
     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);
    }
}

 

猜你在找的Android相关文章