Code
Add a button in the layout file, set listening events for button in the main class, and play music through intent
1. Write activity_ main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_click"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center"
android:padding="8dp"
android:text="@string/click4" />
</LinearLayout>
2. Import music into virtual machine
There is a device file explorer in the lower right corner of Android studio. After opening, you can see the file directory of the virtual machine. Find/MNT/sdcard/music, right-click upload and select the music to be imported. The file name should not appear in Chinese
3. Write mainactivity.class
package com.ch5_2;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import java.io.File;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_click4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//Get the file path, the path is the virtual machine memory card path
Uri data = Uri.fromFile(new File("/mnt/sdcard/Music/nogoodbye.mp3"));
intent.setDataAndType(data,"audio/*");
startActivity(intent);
}
});
}
}
Questions
1. Flashback
Here, the version of the virtual machine will affect the operation. If the version is too high, it will flash back. I used to use Android 11.0, but as soon as I click button, it will flash back. The reason should be the compatibility problem. Change to a lower version
here is Android 5.0
2. This file type problem is not supported
When changing to a lower version of the virtual machine, you may encounter the problem that Android music playing software does not support this type of file. I used MP3 file at the beginning, and the result shows that it does not support it. It’s OK to change to WAV format.