) Android operation sdcard multimedia files (2) -- updating the music list

Source: Internet
Author: User
In the previous article, I introduced how to query the multimedia files in the sdcard in the program and display them in the playlist. However, if you delete or add some multimedia files in the sdcard, how can I update the playlist? Here I will share some of my solutions in the project, hoping to help you. First of all, I will briefly introduce how Android scans the multimedia information in the sdcard, please read the stay blog: http://www.cnblogs.com/stay/articles/1957571.html when the Android system started, the system automatically scans the multimedia files in the sdcard and saves the obtained information in a system database. If you want to access the information of the multimedia files in other programs, in fact, it is done in this database, rather than directly accessing sdcard. After understanding this, the problem will also come: if I add or delete some multimedia files in the sdcard when I start the system, will the system automatically scan them once? The answer is no. That is to say, when you change the multimedia files in the sdcard, the system database files that store the multimedia information will not be dynamically updated. So how can we update data in multimedia databases? We can use the broadcast mechanism to implement: Send a broadcast in the application, let the Android system scan the sdcard and update the multimedia database

private void scanSdCard(){
        IntentFilter intentfilter = new IntentFilter( Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentfilter.addDataScheme("file");
        scanSdReceiver = new ScanSdReceiver();
        registerReceiver(scanSdReceiver, intentfilter);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath()))); }

Scansdreceiver is a custom broadcast receiver inherited from broadcastreceiver. Because the Android system starts to scan sdcard and sends a system broadcast to indicate the status of the current scan when the scan is completed, in this way, we can easily add some logic operations by judging the current scan status. The scansdreceiver code is as follows:

public class ScanSdReceiver extends BroadcastReceiver {
 
    private AlertDialog.Builder  builder = null;
    private AlertDialog ad = null;
    private int count1;
    private int count2;
    private int count;
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)){
            Cursor c1 = context.getContentResolver()
            .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media.DURATION,
                    MediaStore.Audio.Media.ARTIST,
                    MediaStore.Audio.Media._ID,
                    MediaStore.Audio.Media.DISPLAY_NAME },
                    nullnullnull);
            count1 = c1.getCount();
            System.out.println("count:"+count);
            builder = new AlertDialog.Builder(context);
            builder.setMessage("Scanning the memory card ...");
            ad = builder.create();
            ad.show();
             
        }else if(Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)){
            Cursor c2 = context.getContentResolver()
            .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media.DURATION,
                    MediaStore.Audio.Media.ARTIST,
                    MediaStore.Audio.Media._ID,
                    MediaStore.Audio.Media.DISPLAY_NAME },
                    nullnullnull);
            count2 = c2.getCount();
            count = count2-count1;
            ad.cancel();
            if (count>=0){
                Toast.makeText(context, "Added in total" +
                        count + "First Song", Toast.LENGTH_LONG).show();
            else {
                Toast.makeText(context, "Reduced in total" +
                        count + "First Song", Toast.LENGTH_LONG).show();
            }  
        }  
    }
}

Here we define two cursor objects, which are used to store the multimedia information before and after scanning, and provide corresponding prompts. Many friends have asked me why the number of data entries in the playlist has not changed after scanning. To update the playlist after scanning, you must re-read the multimedia information to the cursor, reset the adapter, and call xxxadapter. notifydatasetchanged () to notify the UI of updates. (Refer to the first document) the above operations are to manually add or delete multimedia files in the sdcard. The following describes how to delete multimedia files in the sdcard list. In the previous article, we used the contentprovider provided by the system to query multimedia files in sdcard. We can also use this contentprovider to delete the files:

private void deleteMusic(int position){
    this.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Audio.Media._ID + "=" + _ids[position],
            null);
}

The "multimedia file ID" can be obtained from the _ IDs array (for details about the _ IDs array, refer to the first one ). In this way, have we deleted the specified _ id multimedia file from sdcard? In fact, when you open fileexplorer, you will find that the original file is not deleted ,--! The cup is still working on files for a long time. When I encountered this problem for the first time, I also struggled for a long time... The reason is that the above deletion operation only deletes the corresponding records in the system multimedia database, but does not delete the files in sdcaed (note: the multimedia files in the multimedia information database and sdcard are not automatically synchronized.) If you scan sdcard again, you will find that the row you just deleted from the playlist appears again. In fact, it is not difficult to delete multimedia files from sdcard. Some may think of this method: traverse the multimedia files in sdcard and compare the files to be deleted with other files one by one, find the file path and delete it. This method can be used to delete objects, but the efficiency is very low. If there are many folders and files in sdcard, you do not know how long it will take .. In the previous one, we read a very important message from the Multimedia Database: mediastore. audio. media. data and the obtained strings coexist in the _ path array. The final data format is:/sdcard/[subfolder name] file name, we can easily Delete multimedia files from sdcard.

private void deleteMusicFile(int position){
    File file = new File(_path[position]);
    file.delete();
}

Similarly, to synchronously update the playlist after deleting a file, you must perform the operations described earlier.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.