我想要实现的是在用户启动应用程序时播放音乐,当用户进入下一个活动时,音乐会停止(这很有效)。但是,当用户选择后退按钮时,音频应该从主菜单(活动)再次开始播放。现在没有任何事情发生,音乐根本没有发挥。
这是我的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);
}
}
我应该在介绍课程中添加一些内容吗? 任何帮助将不胜感激!!
答案 0 :(得分:0)
你有一个混乱的朋友你在onCreate里面打电话给super.onResumen。
尝试覆盖onResumen并将所有员工放在那里:
@Override
public void onResumen(){
super.onResume();
mp = MediaPlayer.create(this, R.raw.audio);
mp.setLooping(true);
if(mp != null && !mp.isPlaying())
mp.start();
}
因为每次活动再次出现前,就会调用onResumen
答案 1 :(得分:0)
由于您使用startActivityForResult()
启动简介活动,因此在MainActivy.java中覆盖方法onActivityResult(int requestCode, int resultCode, Intent data)
。在此方法中,您可以再次启动音乐。
@Override onActivityResult (int requestCode, int resultCode, Intent data)
{
if(mp != null && !mp.isPlaying())
mp.start();
}