我正在尝试创建一个在后台播放音乐(无线电流)的应用(没有Service
),并且还允许用户将Gif设置为动态壁纸(使用WallpaperService
)。
问题:
WallpaperService
)。我想要什么
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MusicButton = findViewById(R.id.toggleButton);
mediaPlayer = new MediaPlayer();
new PlayerTask().execute("URL");
@SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
}
@Override
protected void onDestroy() {
super.onDestroy();
MApplication.sBus.post(PlaybackEvent.PLAY);
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
MusicButton.setChecked(true);
}
break;
case PAUSE:
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
MusicButton.setChecked(false);
}
break;
}
}
KillNotificationService 如果用户关闭应用
,则取消通知服务public class KillNotificationService extends Service {
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert nMgr != null;
nMgr.cancelAll();
MApplication.sBus.post(PlaybackEvent.PLAY);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
请帮助我,我花了3天时间来解决这个问题而没有任何结果
(抱歉我的英语不好)
答案 0 :(得分:0)
了解活动生命周期here,您将看到活动具有onPause()/ onStop()以及许多此类状态。
如果您想在应用暂时关闭时停止音乐(对我有用): 在主类下创建一个onPause(),然后在其中暂停/停止音乐。
@Override
protected void onPause() {
mediaPlayer.stop();
super.onPause();
}
onStop()也一样。 提示:开始之前,请确保媒体播放器不为null: 谢谢