如何停止在fragmentActivity上播放背景音乐

时间:2017-01-12 16:28:18

标签: android android-fragmentactivity background-music background-media-player

我有一个Mainactivity扩展fragmentActivity(不确定是否相关),它播放背景音乐很好。当你离开活动时我希望音乐停止。我最小化了以下代码。我在Activity的onPause()生命周期中获得了一个nullpoint异常。

public class MainActivitytest extends FragmentActivity implements
    ActionBar.TabListener{

private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private int myShuffledSize;
private Context context;
public static final String PREFS_NAME = "MyPrefsFile";
public MediaPlayer player;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    Intent intent = new Intent(this, MusicService.class);
    startService(intent);

    new SetupViews().invoke();  //setup fragment views
}

public void onResume() {
    super.onResume();
    MediaPlayer player = MediaPlayer.create(MainActivitytest.this, R.raw.bgmusic3);
    player.setLooping(true);
    player.setVolume(100, 100);
    player.start();

}
public void onPause(){
    super.onPause();
    //player.stop();  //causes null pointer exception
}

1 个答案:

答案 0 :(得分:0)

经过更多的研究,我完成了我想要的服务,这是我学到的新东西。这是我使用的代码

public class MainActivitytest extends FragmentActivity implements
    ActionBar.TabListener {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public final static String MUSIC_BACKGROUND = "com.example.myfirstapp.MESSAGE";

private String[] tabs = {"Colors and Shapes", "Letters and Numbers", "CVC and Sight Words", "Adjectives", "Simple Sentences", "Reading Comprehension"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private Context context;
public static final String PREFS_NAME = "MyPrefsFile";

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){

    public void onServiceConnected(ComponentName name, IBinder
            binder) {

        mServ = ((MusicService.ServiceBinder)binder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
    }
};

void doBindService(){
    bindService(new Intent(this,MusicService.class),
            Scon,Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void doUnbindService()
{
    if(mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    Intent intent = new Intent(this, MusicService.class);
    startService(intent);

    new SetupViews().invoke();  //setup fragment views
}

    public void onPause(){
    super.onPause();
    Intent intent = new Intent(this, MusicService.class);
    stopService(intent);

现在我的服务类

package info.androidhive.tabsswipe;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;

public MusicService() {
}

public class ServiceBinder extends Binder {
    public MusicService getService() {
        return MusicService.this;
    }

}

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();

    mPlayer = MediaPlayer.create(this, R.raw.bgmusic3);
    mPlayer.setOnErrorListener(this);

    if (mPlayer != null) {
        mPlayer.setLooping(true);
        mPlayer.setVolume(100, 100);
    }


    mPlayer.setOnErrorListener(new OnErrorListener() {

        public boolean onError(MediaPlayer mp, int what, int
                extra) {

            onError(mPlayer, what, extra);
            return true;
        }
    });
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mPlayer.start();
    return START_STICKY;
}

public void pauseMusic() {
    if (mPlayer.isPlaying()) {
        mPlayer.pause();
        length = mPlayer.getCurrentPosition();

    }
}

public void resumeMusic() {
    if (mPlayer.isPlaying() == false) {
        mPlayer.seekTo(length);
        mPlayer.start();
    }
}

public void stopMusic() {
    mPlayer.stop();
    mPlayer.release();
    mPlayer = null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
    if (mPlayer != null) {
        try {
            mPlayer.stop();
            mPlayer.release();
        } finally {
            mPlayer = null;
        }
    }
    return false;
}


}

将其包含在清单

    <service android:name=".MusicService" />
    <activity
        android:name="info.androidhive.tabsswipe.MainActivitytest"
        android:label="@string/app_name" >


        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

即使在我的碎片视图上也能正常工作。我今天学到了很多东西。希望这有助于像我这样的其他人。