Android 通过 content provider(内容提供者)获取手机媒体存储。
直接上代码:
1:配置权限: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2:获取并显示基本信息:
public class MainActivity extends AppCompatActivity {
private Button button1,button2,button3;
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.getImg);
button2 = (Button)findViewById(R.id.getMusic);
button3 = (Button)findViewById(R.id.getVideo);
textView1 = (TextView)findViewById(R.id.show);
//获取图片
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] str = {
MediaStore.Images.Media._ID,//图片id
MediaStore.Images.Media.DISPLAY_NAME,//图片名称
MediaStore.Images.Media.DATA//图片路径
};
//获取返回的结果集
Cursor cursor = getContentResolver().query(uri,str,null,null,null);
StringBuffer stringBuffer = new StringBuffer();
//读取结果集
while (cursor.moveToNext()){
stringBuffer.append(cursor.getString(0)+"\n");
stringBuffer.append(cursor.getString(1)+"\n");
stringBuffer.append(cursor.getString(2)+"\n");
}
cursor.close();
textView1.setText(stringBuffer.toString());
}
});
//音乐
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] str = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ALBUM,//专辑
MediaStore.Audio.Media.ARTIST,//作者
MediaStore.Audio.Media.DATA
};
Cursor cursor = getContentResolver().query(uri,str,null,null,null);
StringBuffer stringBuffer = new StringBuffer();
while (cursor.moveToNext()){
stringBuffer.append(cursor.getString(0)+"\n");
stringBuffer.append(cursor.getString(1)+"\n");
stringBuffer.append(cursor.getString(2)+"\n");
stringBuffer.append(cursor.getString(3)+"\n");
}
cursor.close();
textView1.setText(stringBuffer.toString());
}
});
//视频
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] str = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA
};
Cursor cursor = getContentResolver().query(uri,str,null,null,null);
StringBuffer stringBuffer = new StringBuffer();
while (cursor.moveToNext()){
stringBuffer.append(cursor.getString(0)+"\n");
stringBuffer.append(cursor.getString(1)+"\n");
stringBuffer.append(cursor.getString(2)+"\n");
}
cursor.close();
textView1.setText(stringBuffer.toString());
}
});
}
}