AndroidStudio通过intent播放sdcard中的音乐时闪退问题

一、代码

在布局文件中添加一个button,在主类中为button设置监听事件,通过intent来播放音乐

1.编写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.往虚拟机中导入音乐

在AndroidStudio的右下角有个Device File Explorer,打开后可以看到虚拟机的文件目录。找到/mnt/sdcard/Music , 右键upload选择要导入的音乐,文件名最好不要出现中文。
AndroidStudio通过intent播放sdcard中的音乐时闪退问题_第1张图片

3.编写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);
                //获得文件路径,路径为虚拟机存储卡路径
                Uri data = Uri.fromFile(new File("/mnt/sdcard/Music/nogoodbye.mp3"));
                intent.setDataAndType(data,"audio/*");
                startActivity(intent);
            }
        });
    }
}

二、问题

1.闪退问题

这里虚拟机的版本会影响运行,如果版本过高会闪退,我之前用的是Android11.0,结果一点击button就闪退,原因应该是兼容问题吧,换个低版本即可
AndroidStudio通过intent播放sdcard中的音乐时闪退问题_第2张图片
这里使用的是Android5.0

2.不支持此文件类型问题

当换了低版本的虚拟机后可能会遇到安卓的音乐播放软件不支持此类型的文件的问题,我这里一开始用的是mp3文件,结果显示不支持,换成wav格式的可以了。

你可能感兴趣的:(android,android,studio,app,安卓)