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

How to stop playing background music on fragmentActivity

我有一个 Mainactivity extends fragmentActivity(不确定是否相关),它可以很好地播放背景音乐。我希望音乐在您离开 activity 时停止。我最小化了下面的代码。我在 Activity.

onPause() 生命周期中收到空点异常
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
}

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

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);

现在我的服务class

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>

这甚至适用于我的碎片化视图。我今天学到了很多。希望这对像我这样的人有帮助。