使用
RemoteViews
自定义通知栏消息视图,当然可以增加几个按钮了,如下图,有两个按钮支持音乐控制:
主要代码如下:
private void updateNotification(String msg) {
RemoteViews remoteView = new RemoteViews(this.getPackageName(),
R.layout.notifyview);
remoteView.setTextViewText(R.id.tracktmsg, msg);
if (mPlayer.isPlaying()) {
remoteView.setImageViewResource(R.id.statusbar_pause,
android.R.drawable.ic_media_pause);
} else {
remoteView.setImageViewResource(R.id.statusbar_pause,
android.R.drawable.ic_media_play);
}
remoteView.setOnClickPendingIntent(R.id.statusbar_pause, PendingIntent
.getService(this, 0, new Intent(ACTION_SERVICE).putExtra("com",
COMMAND.TOGGLE_PLAYBACK), 0));
remoteView.setOnClickPendingIntent(R.id.statusbar_next, PendingIntent
.getService(this, 1, new Intent(ACTION_SERVICE).putExtra("com",
COMMAND.NEXT), 0));
Notification noti = new Notification();
noti.icon = R.drawable.myicon;
noti.flags |= Notification.FLAG_ONGOING_EVENT;
noti.contentView = remoteView;
noti.contentIntent = PendingIntent.getActivity(this, 0, new Intent(
this, PlayActivity.class), 0);
startForeground(NOTIFICATION_ID, noti);//增加优先级,不许移除此通知
}
//必要时使用
stopForeground(true);取消此通知
xml视图资源:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp">
<!- 图标 -->
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@drawable/myicon_small" />
<LinearLayout
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:orientation="vertical">
<TextView
style="@android:style/TextAppearance.StatusBar.EventContent.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
<TextView android:id="@+id/tracktmsg"
style="@android:style/TextAppearance.StatusBar.EventContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical">
<!- 播放暂停 -->
<ImageButton
android:id="@+id/statusbar_pause"
style="@android:style/MediaButton.Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<!- 下一首 -->
<ImageButton
android:id="@+id/statusbar_next"
style="@android:style/MediaButton.Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
注:android 2.2 似乎不可以实现本文效果