我製作了一個定時器按鈕來設置播放音樂片段的時間。我創建了報警管理設定時間,從通知欄停止媒體播放器
AlarmMAnager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
設置10秒
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
10 * 1000, alarmIntent);
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
private CharSequence msg = "Notofication";
MediaPlayer mp;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
mp = MediaPlayer.create(context, R.raw.music);
mp.start();
Intent dismissIntent = new Intent(context,DismissBroadcast.class);
PendingIntent piDismiss = PendingIntent.getBroadcast(context, 100, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test")
.setAutoCancel(true)
.setContentText("test")
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.addAction(R.drawable.ic_cancel_white_36dp,
"Dismiss", piDismiss);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
public MediaPlayer cancelMusic(){
return mp;
}
}
DismissBroadcast.java
public class DismissBroadcast extends BroadcastReceiver {
AlarmReceiver receive;
@Override
public void onReceive(Context context, Intent intent) {
receive.cancelMusic();
receive.mp.stop();
try {
receive.mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
receive.mp.seekTo(0);
}
}
當我點擊解僱button
從notification
吧,應用程序將崩潰。請給我一些想法如何從AlarmReceiver.java
啓動媒體播放器,並從DismissBroadcast.java
停止。
我想你NullPointerException導致'AlarmReceiver接收;'沒有初始值。我認爲你應該將MediaPlayer mp移動到另一個類中,它不應該依賴於AlarmReceiver類。當'AlarmReceiver'接收到數據時 - >調用方法啓動音樂。然後當點擊通知 - >呼叫停止音樂。 – NamNH
我沒聽到你的話。你能解釋更多嗎?請。我是新手,沒有關於廣播的知識。Receiver –