Spotify Android应用程序在通知中播放音乐控件(播放/暂停,下一首歌曲)。
我想让用户通过控件内部通知来控制Service
。我怎么做?
答案 0 :(得分:3)
为此,您需要为通知制作自己的布局。
您可以尝试使用以下代码。
首先为您的通知创建一个xml。
<强> custom_notification.xml:强>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp" >
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/image"
style="Custom Notification Title" />
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/image"
android:layout_below="@id/title"
style="Custom Notification Text" />
</RelativeLayout>
现在是java代码:
public class MainActivity extends Activity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, "Custom Notification", when);
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, "Custom notification");
contentView.setTextViewText(R.id.text, "This is a custom layout");
notification.contentView = contentView;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
mNotificationManager.notify(1, notification);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
答案 1 :(得分:0)
NotificationCompat.Builder.addAction()
向此通知添加操作。系统通常会将操作显示为与通知内容相邻的按钮。 操作按钮不会出现在Android 4.1之前的平台上。