实现在开机后收到如图所示的通知,并且在下拉通知栏中,一点击“the notification”通知,该通知就消失。
通过自定义一个BroadcastReceiver,来接收广播"android.intent.action.BOOT_COMPLETED"和
"com.sec.android.app.simrecord.CLEAR_NOTI_ACTION"。
在收到广播BOOT_COMPLETED,生成一条通知。
在收到广播CLEAR_NOTI_ACTION,清除该通知。
具体代码如下:
public class SimRecordReceiver extends BroadcastReceiver {
private static final String TAG ="simrecord: SimRecordReceiver";
static final int NOTI_ID =0;
private static final String CONTENT_URI ="content://com.sec.provider.simrecord";
private static final String CLEAR_NOTI_ACTION ="com.sec.android.app.simrecord.CLEAR_NOTI_ACTION";
private static final long[] VIBRATE ={0,500};
SimRecordResolver mSimRecordResolver;
Context mContext;
public SimRecordReceiver() {
// TODO Auto-generated constructor stub
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG," onReceive()= " + intent.getAction().toString());
mContext=context;
mSimRecordResolver = new SimRecordResolver(context);
if(CLEAR_NOTI_ACTION.equals(intent.getAction().toString())){
Log.d(TAG," mNotifiManager . cancel() " );
NotificationManager mNotifiManager = (NotificationManager)mContext. getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager.cancel(0);
}
if(("android.intent.action.BOOT_COMPLETED").equals(intent.getAction().toString())){
setNoti();
}
}
public void setNoti(){
Log.d(TAG," onReceive() setNoti()" );
Intent resultIntent = new Intent();
resultIntent.setAction(CLEAR_NOTI_ACTION);
PendingIntent resultPendingIntent = PendingIntent.getBroadcast(mContext, 0, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.sim_icon) //设置图标
.setContentTitle("the notification") //设置标题
.setContentText("the notification: setContentText") //设置在下拉菜单中的显示内容
.setVibrate(VIBRATE) //设置通知到来时的震动提示
.setTicker("the notification: setTicker") //设置在最顶端的显示内容
.setAutoCancel(true)
.setContentIntent(resultPendingIntent); //设置点击通知时,要触发的activity或者broadcast
NotificationManager mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifiManager.notify(0, mBuilder.build()); //发出通知
}
}
1.首先看生成一条通知,主要是通过NotificationCompat.Builder类进行设置。
通过以下方法分别设置了通知的主要信息:
setSmallIcon() / setContentTitle() / setContentText() / setTicker();
最后通过NotificationManager类进行发送通知mNotifiManager.notify(0, mBuilder.build());
其中方法notify(int id, Notification notification)中的参数分别代表以下意义:
id:在通知移除的时候,也是根据该值进行移除的,类似于此条通知的身份证。
notification: 是需要发出的通知,在这里我们通过NotificationCompat.Builder类的build()方法进行初始化通知。
2.实现点击通知,然后通知移除。
a. 首先初始化一个Intent,设置该Intent的Action为CLEAR_NOTI_ACTION
b.通过PendingIntent类的方法getBroadcast(),得到一个PendingIntent。该方法类似于Context.sendBroadcast().
如果是要实现点击通知跳转到另外一个activity,那么就可以通过PendingIntent类的方法getActivity(),得到一个PendingIntent。
c. 最后NotificationCompat.Builder类的setContentIntent(), 将该PendingIntent设置到通知去。
d.SimRecordReceiver收到Action为CLEAR_NOTI_ACTION的Intent,对通知进行移除mNotifiManager.cancel(0);