package com.example.demo_mediascanner; import java.io.File; import java.util.Calendar; import java.util.Date; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.util.Log; import android.view.Menu; import android.view.View; /** * 扫描音乐 --scanner music * @author alan * */ public class MainActivity extends Activity { private Cursor cursor ; Calendar cal = Calendar.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED); intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentfilter.addDataScheme("file"); MediaScannerReceiver receiver = new MediaScannerReceiver(); registerReceiver(receiver, intentfilter); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); } public void scanFileAsync(Context ctx, String filePath) { Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); scanIntent.setData(Uri.fromFile(new File(filePath))); ctx.sendBroadcast(scanIntent); } public void scanner(View view){ cursor = getContentResolver(). query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); Thread thread = new Thread(){ int n; @Override public void run() { while (cursor.moveToNext()) { //歌曲的名称 :MediaStore.Audio.Media.TITLE String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); //歌曲文件的路径 :MediaStore.Audio.Media.DATA String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); //方法1:歌曲文件的修改时间 (注意:精确到秒,所以还要*1000):MediaStore.Audio.Media.DATE_MODIFIED long updateTime= cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED)); updateTime = updateTime*1000; //方法2:获取最新修改时间 File file = new File(url); long time = file.lastModified(); //格式化时间,获取年,月,日 String[] times = getTimeInfo(updateTime); // Log.i("TAG", "tilte:"+tilte); Log.i("TAG", "url:"+url); Log.i("TAG", "times:"+times[0]+times[1]+times[2]); n++; } Log.i("TAG", "n====>"+n); Log.i("TAG", "getCount====>"+cursor.getCount()); } }; thread.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * 获取时间(年月日) * @return */ public String[] getTimeInfo(long time){ String[] times = new String[3]; Date date = new Date(time); cal.setTime(date); times[0] = cal.get(Calendar.YEAR)+""; times[1]= (cal.get(Calendar.MONTH)+1)+"";//calendar月份从0-11 times[2]= cal.get(Calendar.DAY_OF_MONTH)+""; return times; } }
时间: 2024-10-10 07:25:43