Background music Android

后端 未结 9 1417
夕颜
夕颜 2020-12-03 01:57

Okey, this is my problem. I have one service class where Ive managed to create media player to play music in background all time. Here is code:

package com.t         


        
相关标签:
9条回答
  • 2020-12-03 02:36

    Sure, your service runs in background and you have to stop it manually from your activity when it goes to background.

    0 讨论(0)
  • 2020-12-03 02:36

    write below code in your on stop method:

    system. exit(0);

    this will terminate your media player when you press back/home button or close application

    0 讨论(0)
  • 2020-12-03 02:37

    Try to insert player.stop() in onDestroy() method. It should help.

    0 讨论(0)
  • 2020-12-03 02:41

    AsyncTasks are good just for very short clips, but if it is a music file you will face problems like:

    • You will not be able to stop/pause the music in middle. For me that is a real problem.

    Here is few line from Android developers page about AsyncTasks

    AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

    So currently I am looking in to other options and update the answer once I find the solution.

    0 讨论(0)
  • 2020-12-03 02:42

    Try to insert stopService(svc) in onDestroy() method of the activity in which service starts. It works for me.

    0 讨论(0)
  • 2020-12-03 02:43

    Try following to stop the background music at HOME or BACK press.

    @Override
    protected void onStop() {
        super.onStop();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> services = activityManager
                .getRunningTasks(Integer.MAX_VALUE);
        boolean isActivityFound = false;
    
        if (services.get(0).topActivity.getPackageName().toString()
                .equalsIgnoreCase(getPackageName().toString())) {
            isActivityFound = true; // Activity belongs to your app is in foreground.
        }
    
        if (!isActivityFound) {
            if (player != null && player.isPlaying()) {
                player.release();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题