您的位置:首页 > 移动开发 > Android开发

[android] notification入门

2016-04-04 11:12 399 查看
通知栏,对话框,Toast是我们接触的三个提示框,通知栏是在系统的应用com.adnroid.systemui当中的

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

ACTIVITY_SERVICE,LAYOUT_INFLATER_SERVIC,TELEPHONY_SERVICE,

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

调用NotificationManager对象的notify()方法,发送通知,参数:id是0,Notification对象

获取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对象,通过PendingIntent的getActivity()方法,获取到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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: