一、基本实例
1、在通知栏上的应用—自定义通知栏
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher_background;
notification.tickerText = "hello word";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, AnotherActivity_1.class);
/**
* PendingIntent类似Intent,是一种即将发生的
* 有getActivity/getService/getBroadcast方法,参数分别为:context,requestCode(0),intent,flags---有四种
*
*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextViewText(,);//设置名字和图片
remoteViews.setImageViewResource(,);
//用于点击
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AnotherActivity_2.class),PendingIntent.FLAG_UPDATE_CURRENT );
remoteViews.setOnClickPendingIntent(,openActivity2PendingIntent);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(2, notification);
2、在桌面小部分上应用——-
二、内部机制
通知栏由NotificationManager管理,而NotificationManager通过Binder和SystemServer里的NotificationManagerService进行通信。Manger是在Service里加载的,而Service是在系统的SytemServer中。
RemoteViews会通过Binder传递到SystemServer,然后根据RemoteViews里的包名加载资源。通过LayoutInflater加载布局文件。通过set方法进行更新。
内部更新机制--本地传递Action,远程端解析
三、不同应用间更新UI
A、B两个Activity,在不同进程中运行。
B创建RemoteView对象,A显示出来。两者通过广播通信。
B发送RemoteView代码如下:
A接收广播并更新View代码如下:
public class MainActivity extends AppCompatActivity {
private LinearLayout mRemoteViewsContent;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = intent.getParcelableArrayExtra(MyConstants.EXTRA_REMOTE_VIEWS);//获取remoteView
if (remoteViews != null) {
updateUI(remoteViews);
}
}
};
private void updateUI(RemoteViews remoteViews) {
// /**
// * 同应用用这个
// */
// View view = remoteViews.apply(this, mRemoteViewsContent); //加载并更新View
// mRemoteViewsContent.addView(view);
/**
* 跨应用用这个
*/
int layoutId = getResources().getIdentifier("layout_simulated_notification", "layout", getPackageName());
View view = getLayoutInflater().inflate(layoutId, mRemoteViewsContent,false);//加载View
remoteViews.reapply(this, view);//只是更新View
mRemoteViewsContent.addView(view);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mRemoteViewsContent = (LinearLayout) findViewById(R.id.remote_views_content);
IntentFilter filter = new IntentFilter(MyConstants.REMOTE_ACTION);//这个是用于接收广播的
registerReceiver(broadcastReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastRecei