1
我想在android中創建音樂播放器。這段代碼是讀取mp3文件的SD卡並在烤麪包片中顯示它們。Android中的Mp3 /音樂播放器
當我在手機上運行此應用程序時,手機會顯示一個空白屏幕,即不顯示歌曲。
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String items;
final int READ_EXTERNAL_STORAGE_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST);
return;
}
ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
for(int i = 0; i < mySongs.size(); i++) {
toast(mySongs.get(i).getName().toString());
}
}
public ArrayList<File> findSongs(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for(File singleFile : files) {
if(singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
}
else {
if(singleFile.getName().endsWith(".mp3")) {
al.add(singleFile);
}
}
}
return al;
}
public void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode) {
case READ_EXTERNAL_STORAGE_REQUEST: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
return;
}
}
}
}
謝謝!除了我必須將權限請求從WRITE_EXTERNAL_STORAGE更改爲READ_EXTERNAL_STORAGE以外,一切正常。感謝你的幫助。 –