如果此问题之前已重复过1000次,请道歉,但我确实陷入困境并需要帮助:/。
[问题]
QUESTION 1: Where in the coding I need to add or change to make my background music play automatically when app starts?
就像现在一样,我只能通过使用START按钮来播放它,它也可以播放我的其他活动,这也是我想要它做的。
QUESTION 2: If I want more than one music file to be played, what should be implemented?
(我知道我需要为此创建一个新问题,但只是想到是否可以将这两者合并为一个Q,这会更容易)。
MusicService.java
public class MyService extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer = MediaPlayer.create(this, R.raw.mrkrabs);
mediaPlayer.setLooping(true);
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}//onStartCommand ends here
@Override
public boolean stopService(Intent name) {
return super.stopService(name);
}//stopService ends here
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}//onDestroy ends here
}//MyService ends here
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button stopMusic;
Button startMusic;
Button nextActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stopMusic = (Button) findViewById(R.id.stopMusic);
stopMusic.setOnClickListener(this);
startMusic = (Button) findViewById(R.id.startMusic);
startMusic.setOnClickListener(this);
nextActivity = (Button) findViewById(R.id.nextActivity);
nextActivity.setOnClickListener(this);
}//onCreate ends here
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.stopMusic:
stopService(new Intent(this, MyService.class));
stopMusic.setVisibility(View.GONE);
startMusic.setVisibility(View.VISIBLE);
break;
case R.id.startMusic:
startService(new Intent(this, MyService.class));
startMusic.setVisibility(View.GONE);
stopMusic.setVisibility(View.VISIBLE);
break;
case R.id.nextActivity:
startActivity(new Intent(this, NextActivity.class));
break;
}//switch ends here
}//onClick ends here
}//MainActivity ends here
的Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.musicapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
<activity android:name=".NextActivity"></activity>
</application>
</manifest>
答案 0 :(得分:0)
请确保您正确创建媒体播放器,设置源,准备/循环使用中的呼叫。 Refer this
您可以在活动中使用ServiceConnection并传递来源并更改活动中的来源。这就是典型的音乐应用程序所做的。