[置顶] Android中Notification的使用

时间:2022-05-02 18:56:12

本人入行时间短,自知能力有限,写博客只是为了方便以后工作项目开发中的实用,毕竟都是自己在实际项目开发中亲身实现的功能。另一方面本人工作中只是个小小的码农,也没多少时间好好整理,等闲暇下来会定期不定期的好好修改,毕竟写的不是很专业,可能只有自己能看懂吧。[置顶]        Android中Notification的使用

如想学到更多有关notification的有关用法,本人推荐以下博客:

http://blog.csdn.net/vipzjyno1/article/details/25248021/

http://www.cnblogs.com/travellife/p/Android-Notification-xiang-jie.html

http://www.itnose.net/detail/6169442.html

本人的博客很简单,就是简单整理了一些平时经常看到的Notification的用法。

首先需要创建一个NotificationManager来管理通知:

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
为了保证程序在所有的Android系统版本上都能正常工作,推荐使用support-v4库中的NotificationCompat类创建Notification,

Notification notification = new NotificationCompat.Builder(getApplication()).build();
1.普通样式通知栏

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(getApplication())
.setContentTitle("普通样式通知栏")//通知栏的标题
.setContentText("我是一个普通样式通知栏!")//通知栏的内容
.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知自动取消
.setTicker("你有新的通知!")//通知首次出现在通知栏,带上升动画效果
.setPriority(NotificationCompat.PRIORITY_MAX)//设置通知的优先级
.setDefaults(Notification.DEFAULT_ALL)//给通知添加声音、闪光灯和震动效果,不过单独设置震动效果需要添加系统权限
.setWhen(System.currentTimeMillis())//指定通知产生的时间,会在通知信息里显示
.setSmallIcon(R.drawable.alarm_tick)//设置通知的小图标,显示在系统状态栏上
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.alarm_tick))//设置通知的大图标,当下拉系统状态栏时显示
.build();
manager.notify(1, notification);//让通知显示出来

2.常驻样式通知栏

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pi = PendingIntent.getActivity(getApplication(), 0, getIntent(), 0);//执行跳转动作,getBroadcast、getService等
Notification notification = new NotificationCompat.Builder(getApplication())
.setContentTitle("常驻样式通知栏")//通知栏的标题
.setContentText("使用cancel方法才可以去掉!")//通知栏的内容
.setTicker("常驻通知来了!")//通知首次出现在通知栏,带上升动画效果
.setContentIntent(pi)//执行跳转动作
.setDefaults(Notification.DEFAULT_ALL)//给通知添加声音、闪光灯和震动效果,不过单独设置震动效果需要添加系统权限
.setWhen(System.currentTimeMillis())//指定通知产生的时间,会在通知信息里显示
.setSmallIcon(R.drawable.alarm_tick)//设置通知的小图标,显示在系统状态栏上
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.alarm_tick))//设置通知的大图标,当下拉系统状态栏时显示
.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;//在顶部常驻
manager.notify(1, notification);//让通知显示出来

常驻样式通知栏关键代码就是 notification.flags = Notification.FLAG_ONGOING_EVENT;只有通过调用cancel方法才能清除。

manager.cancel(id);是清除一个特定的ID对应的通知;manager.cancelAll();是清除你发的所有通知。

3.跳转到指定Activity样式的通知栏

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(getApplication(), PlanActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplication(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);//执行跳转动作,
Notification notification = new NotificationCompat.Builder(getApplication())
.setContentTitle("界面跳转样式通知栏")//通知栏的标题
.setContentText("我可以跳转到其他Activity界面!")//通知栏的内容
.setTicker("开始跳转Activity界面了!")//通知首次出现在通知栏,带上升动画效果
.setContentIntent(pi)//执行跳转动作
.setDefaults(Notification.DEFAULT_ALL)//给通知添加声音、闪光灯和震动效果,不过单独设置震动效果需要添加系统权限
.setWhen(System.currentTimeMillis())//指定通知产生的时间,会在通知信息里显示
.setSmallIcon(R.drawable.alarm_tick)//设置通知的小图标,显示在系统状态栏上
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.alarm_tick))//设置通知的大图标,当下拉系统状态栏时显示
.build();
manager.notify(1, notification);//让通知显示出来

跳转Activity界面样式通知栏关键还是靠PendingIntent类,getBroadcast()方法和getService()方法是类同的。

4.下载安装APK样式通知栏

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent apkIntent = new Intent();
apkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
apkIntent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + "/sdcard/solitaire.apk");
apkIntent.setDataAndType(uri, "application/vnd.android.package-archive");
PendingIntent pi = PendingIntent.getActivity(getApplication(), 0, apkIntent, 0);//执行跳转动作,
Notification notification = new NotificationCompat.Builder(getApplication())
.setContentTitle("安装APK样式通知栏")//通知栏的标题
.setContentText("安装APK程序!")//通知栏的内容
.setTicker("点击安装APK程序了!")//通知首次出现在通知栏,带上升动画效果
.setContentIntent(pi)//执行跳转动作
.setDefaults(Notification.DEFAULT_ALL)//给通知添加声音、闪光灯和震动效果,不过单独设置震动效果需要添加系统权限
.setWhen(System.currentTimeMillis())//指定通知产生的时间,会在通知信息里显示
.setSmallIcon(R.drawable.alarm_tick)//设置通知的小图标,显示在系统状态栏上
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.alarm_tick))//设置通知的大图标,当下拉系统状态栏时显示
.build();
manager.notify(1, notification);//让通知显示出来
关键代码就是

Uri uri = Uri.parse("file://" + "/sdcard/solitaire.apk");
apkIntent.setDataAndType(uri, "application/vnd.android.package-archive");

只要找准需要安装程序的路径和设置是安装程序的意图就可以了。
4.进度条样式通知栏

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.xly.base.commons.BaseActivity;
import com.xly.main.R;

public class MainActivity extends BaseActivity implements OnClickListener{

private Button start;
private Button stop;
private Button cancel;
private NotificationManager manager;
/** 通知的ID */
int notifyId = 102;
/** 通知的进度条数值 */
int progress = 0;
private NotificationCompat.Builder mBuilder;
/** 下载线程是否暂停 */
public boolean isPause = false;
private DownloadThread downloadThread;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
initNotify();
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
cancel = (Button) findViewById(R.id.cancel);
start.setOnClickListener(this);
stop.setOnClickListener(this);
cancel.setOnClickListener(this);
}

private void initNotify() {
mBuilder = new NotificationCompat.Builder(this);
PendingIntent pi = PendingIntent.getActivity(getApplication(), 0, getIntent(), 0);
mBuilder.setWhen(System.currentTimeMillis())////指定通知产生的时间,会在通知信息里显示
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_DEFAULT)//设置优先级
.setOngoing(false)//true表示该通知正在进行
.setDefaults(Notification.DEFAULT_VIBRATE)//设置为震动效果
.setSmallIcon(R.drawable.alarm_tick)//设置状态栏图标
.setTicker("开始下载");// 通知首次出现在通知栏,带上升动画效果的
}

/*
* 开始下载
*/
public void startDownloadNotify(){
isPause = false;//下载线程没有暂停
if (downloadThread != null && downloadThread.isAlive()) {
//线程执行过程中不用做任何操作
}else{
//线程没有执行就创建新线程并启动线程
downloadThread = new DownloadThread();
downloadThread.start();
}
}

/*
* 暂停下载
*/
public void stopDownloadNotify(){
isPause = true;
mBuilder.setContentTitle("下载已暂停");
setNotify(progress);
}

/*
* 取消下载
*/
public void cancelDownloadNotify(){
if (downloadThread != null) {
downloadThread.interrupt();
}
downloadThread = null;
mBuilder.setContentTitle("下载已取消!").setProgress(0, 0, false);
manager.notify(notifyId, mBuilder.build());
}

/**
* 设置下载进度
*/
public void setNotify(int progress) {
mBuilder.setProgress(100, progress, false); //第一个参数为进度的最大值,第二个参数代表进度的当前值,,第三个参数代表是否为确定样式
manager.notify(notifyId, mBuilder.build());
}

/**
* 下载线程
*/
class DownloadThread extends Thread {
@Override
public void run() {
int now_progress = 0;
while (now_progress <= 100) {
if(downloadThread == null){
break;
}
if (!isPause) {
progress = now_progress;
mBuilder.setContentTitle("下载中......");
now_progress += 10;
}
try {
Thread.sleep(1000);//休眠1s
} catch (InterruptedException e) {
}
}
if(downloadThread != null){
mBuilder.setContentTitle("下载完成!")
// 下载完成移除进度条
.setProgress(0, 0, false);
manager.notify(notifyId, mBuilder.build());
}
}
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
startDownloadNotify();
break;
case R.id.stop:
stopDownloadNotify();
break;
case R.id.cancel:
cancelDownloadNotify();
break;
}
}
}

5.自定义样式通知栏

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//设定RemoteViews
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_view);
remoteViews.setImageViewResource(R.id.notification_icon, R.drawable.alarm_tick);
remoteViews.setTextViewText(R.id.notification_title, "今日头条");
remoteViews.setTextViewText(R.id.notification_content, "金州勇士官方宣布球队已经解雇了主帅马克-杰克逊,随后宣布了最后的结果。");
remoteViews.setViewVisibility(R.id.notification_time, View.VISIBLE);//显示设置
Notification notification = new NotificationCompat.Builder(getApplication())
.setContent(remoteViews)//把自定义的视图放到通知里
.setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
.setTicker("你有新的消息!")
.setPriority(Notification.PRIORITY_MAX)//设置通知的优先级
.setOngoing(false)//设置为不是正在进行的,true为正在进行 ,效果和.flag一样
.setSmallIcon(R.drawable.alarm_tick)
.build();//把通知显示出来
manager.notify(1, notification);

自定义的界面布局为:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ImageView
android:id="@+id/notification_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="5dp"
android:contentDescription="@null"
android:src="@drawable/alarm_tick"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/notification_title"
style="@style/NotificationTitle"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="标题"
android:textSize="15sp"
/>
<TextView
android:id="@+id/notification_time"
style="@style/NotificationTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15:49"
android:textSize="12sp"
/>
</LinearLayout>
<TextView
android:id="@+id/notification_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/NotificationContent"
android:layout_marginTop="1dp"
android:text="内容"
android:textSize="12sp"
/>
</LinearLayout>
</LinearLayout>

里面用到的style为:

<style name="NotificationContent">
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>

<style name="NotificationTitle">
<item name="android:textColor">?android:attr/textColorPrimary</item>
<item name="android:textStyle">bold</item>
</style>

其实跟普通样式通知栏相比,就是设置了RemoteViews组件。

6.自定义带按钮样式通知栏(音乐播放样式的通知栏)

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.xly.base.commons.BaseActivity;
import com.xly.main.R;

public class MainActivity extends BaseActivity implements OnClickListener{

private Button start;
/** Notification 的ID */
int notifyId = 101;
/** NotificationCompat 构造器*/
NotificationCompat.Builder mBuilder;
/** 是否在播放*/
public boolean isPlay = false;
/** 通知栏按钮广播 */
public ButtonBroadcastReceiver bReceiver;
/** 通知栏按钮点击事件对应的ACTION */
public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
bReceiver = new ButtonBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_BUTTON);
registerReceiver(bReceiver, filter);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(this);
}

@Override
public void onClick(View v) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplication());
//设定RemoteViews
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_view);
remoteViews.setImageViewResource(R.id.song_icon, R.drawable.alarm_tick);
remoteViews.setTextViewText(R.id.song_singer, "叶时伟");
remoteViews.setTextViewText(R.id.song_name, "屌丝的梦想");
/*
* API3.0 以上的时候才会显示按钮
* 如果版本号低于(3。0),那么不显示按钮
*/
if(BaseTools.getSystemVersion() <= 9){
remoteViews.setViewVisibility(R.id.ll_button, View.GONE);
} else {
remoteViews.setViewVisibility(R.id.ll_button, View.VISIBLE);
}

//点击的事件处理
Intent buttonIntent = new Intent(ACTION_BUTTON);
/* 上一首按钮 */
buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
PendingIntent intentPrev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.prev, intentPrev);
/* 播放/暂停按钮 */
buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
PendingIntent intentPlay = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.play, intentPlay);
/* 下一首按钮 */
buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
PendingIntent intentNext = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.next, intentNext);
mBuilder.setContent(remoteViews)//把自定义的视图放到通知里
.setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
.setTicker("你有新的消息!")
.setPriority(Notification.PRIORITY_MAX)//设置通知的优先级
.setOngoing(false)//设置为不是正在进行的,true为正在进行 ,效果和.flag一样
.setSmallIcon(R.drawable.alarm_tick);//把通知显示出来
manager.notify(1, mBuilder.build());
}

public final static String INTENT_BUTTONID_TAG = "ButtonId";
/** 上一首 按钮点击 ID */
public final static int BUTTON_PREV_ID = 1;
/** 播放/暂停 按钮点击 ID */
public final static int BUTTON_PALY_ID = 2;
/** 下一首 按钮点击 ID */
public final static int BUTTON_NEXT_ID = 3;
/**
* 广播监听按钮点击时间
*/
public class ButtonBroadcastReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ACTION_BUTTON)){
//通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);
switch (buttonId) {
case BUTTON_PREV_ID:
Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();
break;
case BUTTON_PALY_ID:
String play_status = "";
if(isPlay){
play_status = "开始播放";
}else{
play_status = "已暂停";
}
//showButtonNotify();
Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();
break;
case BUTTON_NEXT_ID:
Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}

}

@Override
protected void onDestroy() {
if (bReceiver != null) {
unregisterReceiver(bReceiver);
}
super.onDestroy();
}

}
用到的界面布局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ImageView
android:id="@+id/song_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="5dp"
android:contentDescription="@null"
android:src="@drawable/alarm_tick"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/song_singer"
style="@style/NotificationTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="歌手"
android:textSize="15sp"
/>
<TextView
android:id="@+id/song_name"
style="@style/NotificationContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="歌名"
android:textSize="12sp"
/>
</LinearLayout>

<LinearLayout
android:id="@+id/ll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
>
<ImageButton
android:id="@+id/prev"
style="@style/btn_style"
android:src="@drawable/prev"
/>
<ImageButton
android:id="@+id/play"
style="@style/btn_style"
android:src="@drawable/play"
/>
<ImageButton
android:id="@+id/next"
style="@style/btn_style"
android:src="@drawable/next"
/>
</LinearLayout>
</LinearLayout>
用到的style资源如下:

<style name="btn_style">
<item name="android:layout_width">48dip</item>
<item name="android:layout_height">48dip</item>
<item name="android:layout_gravity">center|right</item>
<item name="android:background">?android:listChoiceBackgroundIndicator</item>
</style>
判断版本的类如下:

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class BaseTools {
/**
* 获取当前应用版本号
* @param context
* @return version
* @throws Exception
*/
public static String getAppVersion(Context context) throws Exception {
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),0);
String versionName = packInfo.versionName;
return versionName;
}

/**
* 获取当前系统SDK版本号
*/
public static int getSystemVersion(){
/*获取当前系统的android版本号*/
int version= android.os.Build.VERSION.SDK_INT;
return version;
}
}