Android的媒体播放器单服务不会停止播放 [英] Android mediaplayer singleton service won't stop playing

查看:146
本文介绍了Android的媒体播放器单服务不会停止播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的所有活动的背景音乐。当应用程序不前景应该停止。当我正在开发2.3我不能使用ActivityLifeCycleCallBacks类。我实现的解决方案,<一个href=\"http://stackoverflow.com/questions/3667022/android-is-application-running-in-background/5862048#5862048\">Android:在后台?运行的应用程序,然后决定把媒体播放器独立的,并在服务中使用它。

一切工作正常,如果我preSS回家,从菜单中选择退出或我的应用程序中去后台任何声音停止,但... 一些随机的时间后,当我在做别的事情甚至当屏幕关闭音乐将再次启动出蓝色。即使我杀了从任务管理器应用程序将稍后再重新开始。

这是我的第一单和我第一次玩的服务,所以我想我失去了真正的基本的东西。我想我关闭该服务,但显然我不是。
这里是code:

PlayAudio.java

 进口...
公共类PlayAudio延伸服务{
    私有静态最终意向意图= NULL;
    MediaPlayer的objPlayer;
    私人诠释长度= 0;
    布尔mIsPlayerRelease =真;
    私有静态PlayAudio uniqueIstance; //单身
    静态PlayAudio MSERVICE;
    静态布尔mBound = FALSE; //布尔检查是否包含此单的服务绑定到某个活动
    公共静态布尔activityVisible; //布尔检查是否使用播放器的活动前景或不//我试图让一个单身
公共静态PlayAudio getUniqueIstance(){
    如果(uniqueIstance == NULL){
        uniqueIstance =新PlayAudio();
    }
    返回uniqueIstance;
}
公共静态布尔isActivityVisible(){
    返回activityVisible;
  }  公共静态无效activityResumed(){
    activityVisible = TRUE;
  }  公共静态无效activityPaused(){
    activityVisible = FALSE;
  }
该活动静态公共ServiceConnection mConnection =新ServiceConnection(){//帮手    公共无效onServiceConnected(组件名类名,
            的IBinder服务){
        LocalBinder粘结剂=(LocalBinder)服务;
        MSERVICE = binder.getService();
        mBound = TRUE;
    }    公共无效onServiceDisconnected(组件名称为arg0){
        mBound = FALSE;
    }
};
公共静态意图createIntent(上下文的背景下){//帮手活动使用播放器
    意向意图=新意图(背景下,PlayAudio.class);
    返回意图;
}
私人最终的IBinder mBinder =新LocalBinder();公共类LocalBinder扩展粘结剂{
    PlayAudio的getService(){
        //返回这个实例,以便客户端可以调用的公共方法
        返回PlayAudio.this;
    }
}
@覆盖
公众的IBinder onBind(意向意图){
    返回mBinder;
}
公共无效的onCreate(){
    super.onCreate();
    Log.d(logcat中,服务开始!);
    objPlayer = MediaPlayer.create(这一点,R.raw.kickstarterreduced);
    objPlayer.setLooping(真);
    mIsPlayerRelease = FALSE;
}公众诠释onStartCommand(意向意图,诠释标志诠释startId){
    objPlayer.start();
    Log.d(logcat中,媒体播放器开始了!);
    如果(objPlayer.isLooping()!= TRUE){
        Log.d(logcat中,问题在播放音频);
    }
    返回1;
}公共无效的onStop(){
    objPlayer.setLooping(假);
    objPlayer.stop();
    objPlayer.release();
    mIsPlayerRelease = TRUE;
}公共无效的onPause(){
    如果(objPlayer.isPlaying())
    {
        objPlayer.pause();
        长度= objPlayer.getCurrentPosition(); //保存次序中的位置,以便能够从这里恢复
    }
}
公共无效resumeMusic()//如果长度为0的玩家只要从零开始
{如果(mIsPlayerRelease ==真){
    objPlayer = MediaPlayer.create(这一点,R.raw.kickstarterreduced);
    mIsPlayerRelease = FALSE;
}
    如果(objPlayer.isPlaying()== FALSE)
    {
        如果(长度= 0!)objPlayer.seekTo(长);
        objPlayer.start();
    }
}}

这是我在每个活动的类实现的方法

 共享preferences共享preFS;
PlayAudio playerIstanced;
公共静态布尔activityVisible;
@覆盖
公共无效调用onStart(){
    super.onStart();
    共享preFS = preferenceManager.getDefaultShared preferences(本);
   }
@覆盖
公共无效onResume(){
       super.onResume();
       playerIstanced = PlayAudio.getUniqueIstance(); //调用单
       bindService(PlayAudio.createIntent(本),playerIstanced.mConnection,Context.BIND_AUTO_CREATE); //创建服务
       如果(共享prefs.getBoolean(声音,真)==真){//如果声音选项中启用将启动服务
           startService(PlayAudio.createIntent(本));
           playerIstanced.mService.activityResumed();
           如果(playerIstanced.mBound ==真){
           playerIstanced.mService.resumeMusic();
           }
       }   }
   @覆盖
   公共无效的onPause(){
       super.onPause();
       playerIstanced.mService.activityPaused();
       最后的处理程序处理程序=新的处理程序();
       handler.postDelayed(新的Runnable(){
         公共无效的run(){
           //如果改变活动(的onPause()和其他活动onResume()之间时,电话滞后于音乐不会停止。如果500毫秒后onResume()被不叫这意味着活动后台去了......难道我搞乱服务吗?
             如果(playerIstanced.mService.isActivityVisible()!= TRUE){
                 playerIstanced.mService.onPause();
             }
         }
       },500);}
   @覆盖
   公共无效的onStop(){
       super.onStop();
       //取消绑定从服务
       如果(playerIstanced.mService.mBound){
           playerIstanced.mService.mBound = FALSE;
           unbindService(playerIstanced.mService.mConnection);       }
   }}


解决方案

音乐停止时自动从应用程序用户出口

这部分必须在每一个活动的的onPause:

 公共无效的onPause(){
    super.onPause();
        上下文的背景下= getApplicationContext();
                ActivityManager AM =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
                清单&LT; RunningTaskInfo&GT; taskInfo = am.getRunningTasks(1);
                如果(!taskInfo.isEmpty()){
                  组件名topActivity = taskInfo.get(0).topActivity;
                  如果(!topActivity.getPackageName()。等于(context.getPackageName())){
                   StopPlayer();
                    Toast.makeText(xYourClassNamex.this,你离开APP音乐停下,Toast.LENGTH_SHORT).show();
                  }
                }
      }

这部分必须在每一个活动的onResume:

时自动恢复用户应用程序播放音乐

 公共无效onResume()
    {
       super.onResume();
     StartPlayer();
    }

希望它可以帮助!
您可以检查<一href=\"http://stackoverflow.com/questions/18094878/how-to-play-mp3-continuosly-when-application-starts-and-stop-when-user-close-app/18094911#18094911\">my根据这个主题可能会SOVE您的问题回答。

I need to have background music in all my activities. It should stop when the application is not foreground. As I'm developing for 2.3 I can't use the ActivityLifeCycleCallBacks class. I implemented the solution at Android: Is application running in background? and then decided to make the mediaplayer a singleton and use it in a service.

Everything works fine and if I press home, select quit from the menu or I make the application go background any way the sound stops but... after some random time when I'm doing something else or even when the screen is turned off the music will start again out of the blue. Even if I kill the application from task manager the will start again later again.

This is my first singleton and my first time playing with service so I guess I'm missing something really basic. I think I'm closing the service but apparently I'm not. Here is the code:

PlayAudio.java

import ...
public class PlayAudio extends Service{
    private static final Intent Intent = null;
    MediaPlayer objPlayer;
    private int length = 0;
    boolean mIsPlayerRelease = true;
    private static PlayAudio uniqueIstance; //the singleton
    static PlayAudio mService;
    static boolean mBound = false; // boolean to check if the service containing this singleton is binded to some activity
    public static boolean activityVisible; // boolean to check if the activity using the player is foreground or not

//My attempt to make a singleton
public static PlayAudio getUniqueIstance(){
    if (uniqueIstance == null) {
        uniqueIstance = new PlayAudio();
    }
    return uniqueIstance;
}
public static boolean isActivityVisible() {
    return activityVisible;
  }  

  public static void activityResumed() {
    activityVisible = true;
  }

  public static void activityPaused() {
    activityVisible = false;
  }
static public ServiceConnection mConnection = new ServiceConnection() {// helper for the activity

    public void onServiceConnected(ComponentName className,
            IBinder service) {
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};
public static Intent createIntent (Context context) { //helper for the activity using the player
    Intent intent = new Intent(context, PlayAudio.class);
    return intent;
}
private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    PlayAudio getService() {
        // Return this instance so clients can call public methods
        return PlayAudio.this;
    }
}
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public void onCreate(){
    super.onCreate();
    Log.d(LOGCAT, "Service Started!");
    objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
    objPlayer.setLooping(true);
    mIsPlayerRelease = false;
}

public int onStartCommand(Intent intent, int flags, int startId){
    objPlayer.start();
    Log.d(LOGCAT, "Media Player started!");
    if(objPlayer.isLooping() != true){
        Log.d(LOGCAT, "Problem in Playing Audio");
    }
    return 1;
}

public void onStop(){
    objPlayer.setLooping(false);
    objPlayer.stop();
    objPlayer.release();
    mIsPlayerRelease = true;
}

public void onPause(){
    if(objPlayer.isPlaying())
    {
        objPlayer.pause();
        length=objPlayer.getCurrentPosition(); // save the position in order to be able to resume from here
    }   
}
public void resumeMusic() // if length is 0 the player just start from zero
{   if (mIsPlayerRelease == true) {
    objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
    mIsPlayerRelease = false;
}
    if(objPlayer.isPlaying()==false )
    {
        if (length != 0) objPlayer.seekTo(length);
        objPlayer.start();
    }
}

}

And this are the methods I have implemented in every activity's class

SharedPreferences sharedPrefs;
PlayAudio playerIstanced;
public static boolean activityVisible;
@Override
public void onStart() {
    super.onStart();
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 
   }
@Override
public void onResume() {
       super.onResume();
       playerIstanced= PlayAudio.getUniqueIstance(); //call singleton
       bindService(PlayAudio.createIntent(this), playerIstanced.mConnection, Context.BIND_AUTO_CREATE); // create the service
       if (sharedPrefs.getBoolean("sound", true) == true) {// if sound is enabled in option it will start the service
           startService(PlayAudio.createIntent(this));
           playerIstanced.mService.activityResumed();
           if (playerIstanced.mBound == true) {
           playerIstanced.mService.resumeMusic();
           }
       }

   }
   @Override
   public void onPause() {
       super.onPause();
       playerIstanced.mService.activityPaused();
       final Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
         public void run() {
           //If the phone lags when changing activity (between onPause() and the other activity onResume() the music won't stop. If after 500ms onResume() is not called it means the activity went background...Am I messing with service here?
             if (playerIstanced.mService.isActivityVisible() != true) {
                 playerIstanced.mService.onPause();
             }
         }
       }, 500);

}
   @Override
   public void onStop(){
       super.onStop();
       // Unbind from the service
       if (playerIstanced.mService.mBound) {
           playerIstanced.mService.mBound = false;
           unbindService(playerIstanced.mService.mConnection);

       }
   }



}

解决方案

Stop music automatically when user exit from app

This part has to be in EVERY activity's onPause:

public void onPause(){
    super.onPause();
        Context context = getApplicationContext();
                ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                if (!taskInfo.isEmpty()) {
                  ComponentName topActivity = taskInfo.get(0).topActivity; 
                  if (!topActivity.getPackageName().equals(context.getPackageName())) {
                   StopPlayer();
                    Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP. MUSIC STOP", Toast.LENGTH_SHORT).show();
                  }
                }
      }

This part has to be in EVERY activity's onResume:

Play music automatically when user resume the app

Public void onResume()
    {
       super.onResume();
     StartPlayer();
    }

Hope it helps!! You can check my answer according to this topic may it will sove your issue.

这篇关于Android的媒体播放器单服务不会停止播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆