我尝试了一百万种方式,但每次我按手机的HOME键时,音乐都会一直播放。我的最后一次尝试是使用应用程序,但我仍然有相同的问题。
这是我的代码。
public class ProvaMusica extends Application {
Intent musica_backGround;
public Background_music musicaDiBackground = new Background_music();
public void avvia(){
//this is the class where i manage mediaplayer//////////
musica_backGround=new Intent(this, Background_music.class);
startService(musica_backGround);
}
public void onDestroy(){
stopService(musica_backGround);
}
}在我的第一个活动中,我使用以下代码来启动音乐
ProvaMusica appState = ((ProvaMusica)this.getApplication());
appState.avvia();现在,我应该怎么做才能让音乐在显示其他活动时播放,并在我的应用程序未显示时使音乐停止?
我希望音乐在从一个活动移动到另一个活动时继续播放,我不想停止音乐,然后在新活动开始时重新启动它。
发布于 2013-01-26 21:39:59
也许我找到了一种混合你们所有人给我的建议的方法。
使用此代码,背景音乐(在本例中由服务管理)仅在用户使用后退按钮关闭应用程序时停止,当用户使用主页按钮关闭应用程序时,以及当用户使用设备的锁定按钮锁定屏幕时关闭屏幕。
我希望有比我更专业、更擅长编程的人来确认这是正确的
在这个类中,我检查我当前的活动是否在前台
public class GestioneApplicazioneInBackground{
public static boolean applicazioneInBackground(final Context context) {
ActivityManager am = (ActivityManager) MainActivity.context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
}在我所有活动的onStop()和onPause()方法中,我都有这样的代码
/// if my app and his activities are in background i stop the service i started in my main/first activity////
if(GestioneApplicazioneInBackground.applicazioneInBackground(this) ){
context_of_the_Intent.stopService(intent);
}
else{
// if my app and his activities are NOT in background i check if user turned off the screen with the lock button of the device//////
PowerManager kgMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean showing = kgMgr.isScreenOn();
if(!showing){
context_of_the_Intent.stopService(intent);
}
}发布于 2013-01-23 20:19:04
我这样做的方式是:
我有一个单例类,它是每个活动调用的SoundManager.
发布于 2013-01-23 20:12:40
您可以拥有一个Application类并在AndroidManifest中设置它。在其onDestroy()回调中,您可以使用stopService()函数来停止服务,也可以通过Intent来启动服务来停止音乐。
https://stackoverflow.com/questions/14479410
复制相似问题