简体   繁体   中英

background music automatically stops

I have made an application with Splash Music. But whenever I go in preferences of app, the music automatically stops, and then never plays untill I restart the application. Same is the case when I open an activity, which tells whether phone is in "Normal" or in "Silent" Mode.

  • What is the reason for this weird behavior? Here is the Splash music code where I check whether to play music or not..

    public class SplashScreen extends Activity{

     MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.splashscreen); mp= MediaPlayer.create(SplashScreen.this, R.raw.got); SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext()); ; if(pref.getBoolean("music", true)) { mp.start(); } if(pref.getBoolean("loop", true)) { mp.setLooping(true); } Thread timer= new Thread() { public void run() { try { sleep(5000); Class ourclass = Class.forName("com.umer.practice2.Menu"); Intent myintent= new Intent(SplashScreen.this,ourclass); startActivity(myintent); } catch(Exception e) { e.printStackTrace(); } } }; timer.start(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); finish(); } 

    }

Thanks

It is because you are creating and playing your mediaplayer object on the main thread. When your activity is getting paused, you are finishing the activity which is stopping your mediaplayer. If you want to keep you music independent of the activity, offshore it to a service.

在服务中运行应该可以为您提供帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM