Java 如何在不打开活动的情况下从通知面板执行预期操作
我是android编码的初学者。我正在做一个mediaplayer项目作为学习练习。我已经设法让mediaplayer在后台播放,并在活动被推到后台时,通过播放/暂停按钮显示通知 现在,我已经在我的活动上创建了onNewIntent(),以从通知面板接收操作。我可以播放和暂停音乐,但在通知时单击这些按钮,它将打开播放器活动。我不知道如何在不打开活动的情况下只执行播放或暂停动作 我的活动:Java 如何在不打开活动的情况下从通知面板执行预期操作,java,android,android-notifications,android-notification-bar,onnewintent,Java,Android,Android Notifications,Android Notification Bar,Onnewintent,我是android编码的初学者。我正在做一个mediaplayer项目作为学习练习。我已经设法让mediaplayer在后台播放,并在活动被推到后台时,通过播放/暂停按钮显示通知 现在,我已经在我的活动上创建了onNewIntent(),以从通知面板接收操作。我可以播放和暂停音乐,但在通知时单击这些按钮,它将打开播放器活动。我不知道如何在不打开活动的情况下只执行播放或暂停动作 我的活动: @Override protected void onNewIntent(Intent intent) {
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (intent.getExtras() != null) {
String tmp;
tmp = intent.getExtras().getString("DO");
if (tmp != null) {
if (tmp.equals("pause")) {
pausePlaying();
}else if(tmp.equals("play")){
startPlaying();
}
else if (tmp.equals("exit")) {
Log.i("onNewIntent", "exit");
finish();
}
}
}
}
NotificationPanel.java(我在其中设置了PendingEvents)
我花了很长时间寻找解决办法。找不到。可能是我没有正确搜索。在此方面的任何帮助都将不胜感激。TIA。作为练习:您可以在活动中安装一个本地
广播接收器
,并在那里播放/暂停音乐。在挂起的意图中使用getBroadcast()
而不是getActivity()
。此外,对于音乐,您可以使用前台服务。作为练习:您可以在活动中使用本地广播接收器,并在那里播放/暂停音乐。在挂起的意图中使用getBroadcast()
而不是getActivity()
。此外,对于音乐,您可以使用前台服务。
public class NotificationPanel{
private Context parent;
private NotificationManager nManager;
private android.support.v4.app.NotificationCompat.Builder nBuilder;
private RemoteViews remoteView;
public NotificationPanel(Context parent) {
// TODO Auto-generated constructor stub
this.parent = parent;
nBuilder = new android.support.v7.app.NotificationCompat.Builder(parent)
.setContentTitle("Transistor")
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true);
remoteView = new RemoteViews(parent.getPackageName(), R.layout.activity_notification_return_slot);
//set the button listeners
setListeners(remoteView);
nBuilder.setContent(remoteView);
nManager = (NotificationManager) parent.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(2, nBuilder.build());
}
public void setListeners(RemoteViews view){
//listener 1
Intent pauseIntent = new Intent(parent,ChannelActivity.class);
pauseIntent.putExtra("DO", "pause");
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pauseIntent.setAction(Intent.ACTION_MAIN);
pauseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent btn1 = PendingIntent.getActivity(parent, 0, pauseIntent, 0);
view.setOnClickPendingIntent(R.id.btn1, btn1);
...
//Similarly Intents are set for other actions
}
}