RemoteViews是一种远程View。RemoteViews表示是一个View结构,它可以在其他进程中显示,由于他在其他进程中显示,为了能够更新他的界面,RemoteViews提供了一组基础操作用于跨进程更新他的界面。
Intent intent = new Intent(this,MainActivity.class);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setTicker("hello world")
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("normal_notifycation")
.setContentText("this is normal_notifycation")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
manager.notify(1,notification);
普通的通知栏很简单,可以看到,Notification也是一种建造者模式。这个以后会说到。
那么来说下remoteviews自定义通知栏用法。
Notification notification1 = new Notification();
notification1.icon = R.mipmap.ic_launcher;
notification1.tickerText = "remoteview";
notification1.when = System.currentTimeMillis();
notification1.flags = Notification.FLAG_AUTO_CANCEL;
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.layout_notifycation);
remoteViews.setTextViewText(R.id.msg, "remoteviews text");
remoteViews.setTextViewText(R.id.open_activity2, "click me");
remoteViews.setImageViewResource(R.id.icon, R.mipmap.ic_launcher);
PendingIntent pendingIntent1 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.open_activity2, pendingIntent1);
notification1.contentView = remoteViews;
notification1.contentIntent = pendingIntent1;
manager.notify(2,notification1);
大致代码就是这样,不过在这里我要说明几点:
使用步奏:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/widget" android:minHeight="84dp" android:minWidth="84dp" android:updatePeriodMillis="86400000" >
</appwidget-provider>
有哪些属性可用呢,看下图,属性的含义就不具体说了。图上很明白
3. 定义小部件实现类
实现类要继承AppWidgetProvider类,这个类就是BroadcastReceiver的子类。这个如下
方法名一步了然,就不多少了,需要的去看任玉刚
4. 在manifast中配置
<receiver android:name=".MyAppWidgetProvider">
<meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_provider_info">
</meta-data>
<intent-filter>
<action android:name="com.gl.action.CLICK"/>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
</receiver>
按上面代码的格式配置就好。这里给出郭神的一个链接小火箭传送门
PendingIntent的匹配规则:
如果两个PendingIntent他们内部的Intent相同并且requestCode也相同,那么这两个PendingIntent就是相同的。Intent相同的规则是:ComponentName和intent-filter都相同。
关于4种flag,看书或者文档。