У меня есть свой музыкальный проигрыватель, и я хочу взаимодействовать с виджетом проигрывателя на экране блокировки, а также с уведомлением. Я создал для моего сеансового класса.
Ex:
Моя идея такова: когда я нажимаю кнопку btnPlay
в моем приложении, я вижу, что она называется public void onPlay()
function в MediaPlayerService.java
через:
MainActivity.java
Intent intent = new Intent(getApplicationContext(),MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);
MediaPlayerService.java
@Override
public void onPlay() {
super.onPlay();
buildNotifacation(generateAction(android.R.drawable.ic_media_pause,"PAUSE",ACTION_PAUSE));
MainActivity activity = MainActivity.instance;
activity.performClick();
}
Когда я удалил: MainActivity activity = MainActivity.instance;
activity.performClick();
-> он работал нормально.
Но когда я добавил его, он не мог работать.
Я хочу управлять музыкальным проигрывателем (Play, Stop, Rewind ...) в моем приложении через MainActivity и MediaPlayerService. Но основная цель - через виджет.
Вот мой код:
MainActivity:
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
static MainActivity instance;
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
btnPlay.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v){
if (mediaPlayer.isPlaying()) {
//if song is running --> pause --> change icon to play
mediaPlayer.pause();
btnPlay.setImageResource(R.drawable.ic_player_play);
**Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);**
} else {
//if song is stop --> start --> change icon to pause
mediaPlayer.start();
btnPlay.setImageResource(R.drawable.ic_player_pause);
**Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PLAY);
startService(intent);**
}
setTimeTotal();
UpdateTimeSong();
}
});
public void performClick() {
btnPlay.post(new Runnable() {
@Override
public void run() {
btnPlay.performClick();
}
});
}
}
MediaPlayerService.java:
public class MediaPlayerService extends Service {
private MediaSession mSession;
public static final String ACTION_PLAY = "action_play";
public static final String ACTION_PAUSE = "action_pause";
public static final String ACTION_REWIND = "action_rewind";
public static final String ACTION_FAST_FORWARD = "action_fast_forward";
public static final String ACTION_NEXT = "action_next";
public static final String ACTION_PREVIOUS = "action_previous";
public static final String ACTION_STOP = "action_stop";
private MediaPlayer mMediaPlayer;
private MediaSessionManager mManager;
private android.media.session.MediaController mController;
MainActivity mActivity = new MainActivity();
ArrayList<Song> arraySong;
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public boolean onUnbind(Intent intent) {
mSession.release();
return super.onUnbind(intent);
}
private void handleIndent(Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_PLAY)) {
mController.getTransportControls().play();
} else if (action.equalsIgnoreCase(ACTION_PAUSE)) {
mController.getTransportControls().pause();
} else if (action.equalsIgnoreCase(ACTION_FAST_FORWARD)) {
mController.getTransportControls().fastForward();
} else if (action.equalsIgnoreCase(ACTION_REWIND)) {
mController.getTransportControls().rewind();
} else if (action.equalsIgnoreCase(ACTION_PREVIOUS)) {
mController.getTransportControls().skipToPrevious();
} else if (action.equalsIgnoreCase(ACTION_NEXT)) {
mController.getTransportControls().skipToNext();
} else if (action.equalsIgnoreCase(ACTION_STOP)) {
mController.getTransportControls().stop();
}
}
private Notification.Action generateAction(int icon, String title, String intentAction) {
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(intentAction);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
return new Notification.Action.Builder(icon, title, pendingIntent).build();
}
private void buildNotifacation(Notification.Action action) {
Notification.MediaStyle style = new Notification.MediaStyle();
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(ACTION_STOP);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Lock Screen Media Example")
.setContentText("Artis Name")
.setDeleteIntent(pendingIntent)
.setStyle(style);
builder.addAction(generateAction(android.R.drawable.ic_media_previous, "Previous", ACTION_PREVIOUS));
builder.addAction(generateAction(android.R.drawable.ic_media_rew, "Rewind", ACTION_REWIND));
builder.addAction(action);
builder.addAction(generateAction(android.R.drawable.ic_media_ff, "Fast Forward", ACTION_FAST_FORWARD));
builder.addAction(generateAction(android.R.drawable.ic_media_next, "Next", ACTION_NEXT));
style.setShowActionsInCompactView(0, 1, 2, 3, 4);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mManager == null) {
initMediaSession();
}
handleIndent(intent);
return super.onStartCommand(intent, flags, startId);
}
private void initMediaSession() {
mMediaPlayer = new MediaPlayer();
mSession = new MediaSession(getApplicationContext(), "example player session");
mController = new android.media.session.MediaController(getApplicationContext(), mSession.getSessionToken());
mSession.setCallback(new MediaSession.Callback() {
@Override
public void onPlay() {
super.onPlay();
**
buildNotifacation(generateAction(android.R.drawable.ic_media_pause, "PAUSE", ACTION_PAUSE));
mMediaPlayer = MediaPlayer.create(MediaPlayerService.this, arraySong.get(0).getFile());
MainActivity activity = MainActivity.instance;
activity.performClick();**
}
@Override
public void onPause() {
super.onPause();
buildNotifacation(generateAction(android.R.drawable.ic_media_play, "PAUSE", ACTION_PLAY));
mMediaPlayer.stop();
}
}
}
}
Когда я нажимал btnPlay
на приложении или кнопку «Воспроизвести» на виджете, приложение останавливалось.
Итак, мой вопрос: я использую правильный метод для виджета Music Player? Если да, может ли кто-нибудь помочь мне решить эту проблему?