配置通知栏时,最重要的事情是如何在布局中获取相应的资源文件和相关控件,这是通过Resources#getIdentifier方法获得的:
private Resources res;
private String packageName;
public MediaNotificationManager(){
packageName = mService.getApplicationContext().getPackageName();
res = mService.getApplicationContext().getResources();
}
private int getResourceId(String name, String className) {
return res.getIdentifier(name, className, packageName);
}
复制代码
由于您需要能够动态配置它,因此需要在通知栏中命名约定相关资源和ID. 例如,我想得到

将白色背景上的ContentView布局文件分配给RemoteView:
RemoteViews remoteView = new RemoteViews(packageName,
getResourceId("view_notify_light_play", "layout"));
复制代码
只要您的布局文件名为view_notify_light_play.xml,就可以正确获取它.
因此,所有不同的布局和不同的资源都是通过getResourceId方法获得的.
更新用户界面分为以下三个步骤:
续订RemoteView,替换旧的RemoteView,将新的RemoteView分配给Notification.contentView和Notification.bigContentView,更新RemoteView的UI并调用NotificationManager.notify(NOTIFICATION_ID,mNotification);刷新.
在开始播放时更新播放/暂停按钮的用户界面:
public void updateViewStateAtStart() {
if (mNotification != null) {
boolean isDark = NotificationColorUtils.isDarkNotificationBar(mService);
mRemoteView = createRemoteViews(isDark, false);
mBigRemoteView = createRemoteViews(isDark, true);
if (Build.VERSION.SDK_INT >= 16) {
mNotification.bigContentView = mBigRemoteView;
}
mNotification.contentView = mRemoteView;
if (mRemoteView != null) {
mRemoteView.setImageViewResource(getResourceId(ID_IMG_NOTIFY_PLAY_OR_PAUSE, "id"),
getResourceId(isDark ? DRAWABLE_NOTIFY_BTN_DARK_PAUSE_SELECTOR :
DRAWABLE_NOTIFY_BTN_LIGHT_PAUSE_SELECTOR, "drawable"));
if (mBigRemoteView != null) {
mBigRemoteView.setImageViewResource(getResourceId(ID_IMG_NOTIFY_PLAY_OR_PAUSE, "id"),
getResourceId(isDark ? DRAWABLE_NOTIFY_BTN_DARK_PAUSE_SELECTOR :
DRAWABLE_NOTIFY_BTN_LIGHT_PAUSE_SELECTOR, "drawable"));
}
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
}
}
复制代码
click事件由RemoteView.setOnClickPendingIntent(PendingIntentendingIntent)方法实现.
如果可以动态配置它,关键是配置PendingIntent.
这个想法是: 如果PendingIntent是从外部传入的,则使用传入的PendingIntent,否则使用默认的PendingIntent.
private PendingIntent startOrPauseIntent;
public MediaNotificationManager(){
setStartOrPausePendingIntent(creater.getStartOrPauseIntent());
}
private RemoteViews createRemoteViews(){
if (startOrPauseIntent != null) {
remoteView.setOnClickPendingIntent(getResourceId(ID_IMG_NOTIFY_PLAY_OR_PAUSE, "id"),
startOrPauseIntent);
}
}
private void setStartOrPausePendingIntent(PendingIntent pendingIntent) {
startOrPauseIntent = pendingIntent == null ? getPendingIntent(ACTION_PLAY_PAUSE) : pendingIntent;
}
private PendingIntent getPendingIntent(String action) {
Intent intent = new Intent(action);
intent.setClass(mService, PlayerReceiver.class);
return PendingIntent.getBroadcast(mService, 0, intent, 0);
}
复制代码
如您所见,完整的代码如上所示. 如果creater.getStartOrPauseIntent()不为空播放器build,请使用creater.getStartOrPauseIntent()
否则,请使用默认值.
我希望你喜欢它! ^ _ ^
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/bofangqi/article-238684-2.html
可能是在等中国放松戒备时进来溜溜就走
在中国想要政商分离不可能