安卓USB挂载,卸载广播接收类

本文介绍如何在安卓系统中实现USB插入和移除时的广播接收,以便在设备连接或断开时执行相应操作,并获取USB设备的目录信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(一)说明:

   接上USB,接收广播;拔掉USB,接收广播。并且可以获得USB的目录打印。方便拓展功能。

(二)步骤:

1.注册

 <receiver 
            android:name="com.harison.receive.USBBroadcastReceiver" 
            >
            <intent-filter android:priority="999" >
                <action android:name="android.intent.action.MEDIA_MOUNTED" >
                </action>
                <action android:name="android.intent.action.MEDIA_EJECT" >
                </action>
                <action android:name="android.intent.action.MEDIA_UNMOUNTED" >
                </action>
                <data android:scheme="file" >
                </data>
            </intent-filter>
        </receiver>

2.类代码

package com.harison.receive;

import java.io.File;
import java.util.HashMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.StatFs;
import android.util.Log;

public class USBBroadcastReceiver extends BroadcastReceiver {


    private static int count = 0;
    private static HashMap<String, Integer> diskDesc = new HashMap<String, Integer>();
    private static final String TAG = "USBBroadcastReceiver";

    public static synchronized void addDiskDesc(String key, Integer value) {
        diskDesc.put(key, value);
    }

    public static synchronized void removeDiskDesc(String key) {
        diskDesc.remove(key);
    }

    public static String formatKey(String value) {
        if (value == null) {
            return null;
        }
        if (!value.startsWith("/")) {
            value = "/" + value;
        }
        if (value.endsWith("/")) {
            value = value.substring(0, value.length() - 1);
            return formatKey(value);
        } else {
            return value;
        }
    }

    /**
     * @param source
     * @return
     */
    public static String splitHeadAndTail(String source) {
        if (source == null) {
            return null;
        }
        if (source.startsWith("/")) {
            source = source.substring(1);
        }
        if (source.endsWith("/")) {
            source = source.substring(0, source.length() - 1);
        }
        return source;
    }

    private static synchronized void initDiskDesc() {
        String parent = "/mnt/usb/";
        File pFile = new File(parent);
        File[] children = pFile.listFiles();
        if (children != null) {
            String str = null;
            for (File file : children) {
                str = file.getName();
                if (str != null) {
                    Log.e(TAG, "find disk " + str);
                    addDiskDesc(parent + str, 0);
                }
            }
        }
    }

    public USBBroadcastReceiver() {
        Log.d(TAG, "AD ----- USBBroadcastReceiver constructor!!!");
        if (count == 0) {
            initDiskDesc();
            count++;
        }

    }

    /**
     * @return disk count
     */
    public static synchronized int getDiskCount() {
        if (diskDesc != null) {
            return diskDesc.size();
        } else {
            return 0;
        }
    }

    /**
     * return disk capacity percent by path
     *
     * @param key
     * @return
     */
    public static synchronized int getDiskCapacityPercent(String key) {
        Integer tmp = diskDesc.get(key);
        if (tmp == null) {
            return -1;
        } else {
            return tmp;
        }
    }

    public static synchronized boolean isDiskExisted(String path) {
        path = formatKey(path);
        if (diskDesc.containsKey(path)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_EJECT)) {
            Uri uri = intent.getData();
            final String path = uri.getPath();

            Log.w(TAG, "path:" + path);

            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                Log.w(TAG, "AD ---- ACTION_MEDIA_MOUNTED:" + path);
                addDiskDesc(path, 0);
                new Thread() {
                    public void run() {
                        try {
                            StatFs sf = new StatFs(path);
                            final int percent = (int) (100 - ((sf.getFreeBlocks() * 100)/ sf.getBlockCount()));
                        } catch (IllegalArgumentException e) {
                            Log.e(TAG, "Error : ", e);
                        }

                    };
                }.start();
            } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
                Log.w(TAG, "AD --- ACTION_MEDIA_UNMOUNTED:" + path);
            } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {

                Log.w(TAG, "AD ---- ACTION_MEDIA_EJECT:" + path);
                removeDiskDesc(path);

            }

        }

    }



}

(三)实验现象
06-12 13:59:06.593: D/USBBroadcastReceiver(2581): USBBroadcastReceiver constructor!!!
06-12 13:59:06.593: E/USBBroadcastReceiver(2581): find disk sda1			<span style="color:#ff6666;">--------------  发现usb</span>

06-12 13:59:06.783: W/USBBroadcastReceiver(2581): AD ---- ACTION_MEDIA_MOUNTED:/mnt/usb/sda1
06-12 13:59:26.168: D/USBBroadcastReceiver(2776): USBBroadcastReceiver constructor!!!
06-12 13:59:26.168: W/USBBroadcastReceiver(2776): path:/mnt/usb/sda1
06-12 13:59:26.168: W/USBBroadcastReceiver(2776): ACTION_MEDIA_EJECT:/mnt/usb/sda1	-<span style="color:#ff0000;">--------------	usb挂载成功
</span>

06-12 13:59:26.188: D/USBBroadcastReceiver(2581): USBBroadcastReceiver constructor!!!
06-12 13:59:26.188: W/USBBroadcastReceiver(2581): path:/mnt/usb/sda1
06-12 13:59:26.188: W/USBBroadcastReceiver(2581): AD ---- ACTION_MEDIA_EJECT:/mnt/usb/sda1  <span style="color:#ff0000;">------------ usb卸载成功</span>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值