我想要实现的是在用户启动应用程序时播放音乐,当用户进入下一个活动时音乐停止(这很好用)。但是,当用户选择后退按钮时,音频应该从主菜单(活动)再次开始播放。现在什么都没有发生,音乐也根本没有播放。
这是我的 MainActivity.java 代码
import java.util.List;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mp = MediaPlayer.create(this, R.raw.audio);
mp.setLooping(true);
super.onResume();
if(mp != null && !mp.isPlaying())
mp.start();
super.onResume();
Button next = (Button) findViewById(R.id.button1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Introduction.class);
startActivityForResult(myIntent, 0);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onPause() {
if (this.isFinishing()){ //basically BACK was pressed from this activity
mp.stop();
}
else{
}
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())) {
mp.stop();
}
else {
mp.stop();
}
}
super.onPause();
}
}
这是我的 Introduction.java 代码
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
public class Introduction extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.introduction);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
我应该在介绍课上添加一些东西吗?任何帮助将不胜感激!!