android 自定义带按钮的Notification及点击事件和伸缩通知栏
Posted 奋斗吧,少年!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 自定义带按钮的Notification及点击事件和伸缩通知栏相关的知识,希望对你有一定的参考价值。
1、自定义一个带按钮的Notification布局:layout_notification;
2、创建Notification:
RemoteViews views = new RemoteViews(getPackageName(),R.layout.layout_nitification); //自定义的布局视图
//按钮点击事件:
PendingIntent homeIntent = PengdingIntent.getBroadcast(this,1,new Intent("action"),PengdingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.btn,homeIntent); //点击的id,点击事件
//创建通知:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext);
mBuilder.setContent(views) //设置布局
.setOngoing(true) //设置是否常驻,true为常驻
.setSmallIcon(R.mipmap.ic_laucher) //设置小图标
.setTicker("通知来了") //设置提示
.setPriority(Notification.PRIORITY_MAX) //设置优先级
.setWhen(System.currentTimeMillis()) //设置展示时间
.setContentIntent(PendingIntent.getBroadcast(this,2,new Intent("action.view"),PengingIntent.FLAG_UPDATE_CURRENT); //设置视图点击事件
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(100,mBuilder.build()) //显示通知: 当前notificationid,当前notification
3、创建NotificationBroadcast接收通知:
public class NotificationBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction(); //动作
collapseStatusBar(context); //收起通知栏
Intent i = new Intent(context,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //必须添加,避免重复打开
if (action.equals("com.xczl.smart.notification.home")){
i.putExtra("flag","home"); //传值
context.startActivity(i);
}
}
public void collapseStatusBar(Context context) {
try {
Object statusBarManager = context.getSystemService("statusbar");
Method collapse;
if (Build.VERSION.SDK_INT <= 16) {
collapse = statusBarManager.getClass().getMethod("collapse");
} else {
collapse = statusBarManager.getClass().getMethod("collapsePanels");
}
collapse.invoke(statusBarManager);
} catch (Exception localException) {
localException.printStackTrace();
}
}
4、MainActivity接收消息:
覆写 onNewIntent():
@Override
protected void onNewIntent(Intent intent) {
String extra = intent.getStringExtra("flag");
if (!TextUtils.isEmpty(extra)){
if (extra.equals("home")){
//接收到值的具体操作
}
}
}
5、配置清单:
MainActivity:设置LanchMode为singleTask
注册Broadcast:
<receiver
android:name="com.xczl.smart.broadcast.NotificationBroadcast"
android:enabled="true">
<intent-filter>
<action android:name="action"/>
<action android:name="action.view"/>
</intent-filter>
</receiver>
配置通知栏伸缩权限:
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>
以上是关于android 自定义带按钮的Notification及点击事件和伸缩通知栏的主要内容,如果未能解决你的问题,请参考以下文章