Android中Notification 提示对话框

2019-12-10 19:14:54王振洲

FLAG_ONE_SHOT表示返回的PendingIntent仅能执行一次,执行完后自动取消
FLAG_NO_CREATE表示如果描述的PendingIntent不存在,并不创建相应的PendingIntent,而是返回NULL
FLAG_CANCEL_CURRENT 表示相应的PendingIntent已经存在,则取消前者,然后创建新的PendingIntent, 这个有利于数据保持为最新的,可以用于即时通信的通信场景
FLAG_UPDATE_CURRENT 表示更新的PendingIntent

使用示例:

//点击后跳转Activity
Intent intent = new Intent(context,XXX.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); 
mBuilder.setContentIntent(pendingIntent) 

setPriority(int):设置优先级:

优先级

用户

MAX

重要而紧急的通知,通知用户这个事件是时间上紧迫的或者需要立即处理的。

HIGH

高优先级用于重要的通信内容,例如短消息或者聊天,这些都是对用户来说比较有兴趣的。

DEFAULT

默认优先级用于没有特殊优先级分类的通知。

LOW

低优先级可以通知用户但又不是很紧急的事件。

MIN

用于后台消息 (例如天气或者位置信息)。最低优先级通知将只在状态栏显示图标,只有用户下拉通知抽屉才能看到内容。

对应属性:Notification.PRIORITY_HIGH..

五、基本使用实例

package com.example.test3;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener{
private Button btn1;
private Button btn2;
// 两个相关类
private NotificationManager manager;
private Notification notification;
private static final int NOTIFYID_1 = 1;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn1:{
// 定义一个PendingIntent,点击Intent可以启动一个新的Intent
Intent intent = new Intent(MainActivity.this,OtherActivity.class);
PendingIntent pit =PendingIntent.getActivity(MainActivity.this,0,intent,0);
// 设置图片文字提示方式等等
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setContentTitle("叶良辰") //标题
.setContentText("我有一百种方法让你呆不下去~") //内容
.setSubText("——记住我叫叶良辰") //内容下面的一小段文字
.setTicker("收到叶良辰发送过来的信息~") //收到信息后状态栏显示的文字信息
.setWhen(System.currentTimeMillis()) //设置通知时间
.setSmallIcon(R.mipmap.ic_account) //设置小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) //设置默认的三色灯与振动器
.setAutoCancel(true) //设置点击后取消Notification
.setContentIntent(pit);
notification = builder.build();
manager.notify(NOTIFYID_1,notification);
break;
}
case R.id.btn2:{
manager.cancel(NOTIFYID_1);
break;
}
}
}
}