Android BroadcastReceiver之监听外置SD卡状态

来源:互联网 发布:python 图片加水印 编辑:程序博客网 时间:2024/06/05 16:08

SD卡状态侦听
* 一个广播接收者可以接受多种广播,定义多个action即可
监听SD卡状态
* 清单文件中定义广播接收者接收的类型,监听SD卡常见的三种状态,所以广播接收者需要接收三种广播

     <receiver android:name="com.cy.sdcradlistener.SDCardReceiver">        <intent-filter >            <action android:name="android.intent.action.MEDIA_MOUNTED"/>            <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>            <action android:name="android.intent.action.MEDIA_REMOVED"/>            <data android:scheme="file"/>        </intent-filter>    </receiver>

* 广播接收者的定义

    public class SDCardReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            // 区分接收到的是哪个广播            String action = intent.getAction();            if(action.equals("android.intent.action.MEDIA_MOUNTED")){                System.out.println("sd卡就绪");            }            else if(action.equals("android.intent.action.MEDIA_UNMOUNTED")){                System.out.println("sd卡被移除");            }            else if(action.equals("android.intent.action.MEDIA_REMOVED")){                System.out.println("sd卡被拔出");            }        }    }
 <receiver android:name="com.cy.sdlistener.SDReceiver">            <intent-filter >                <action android:name="android.intent.action.MEDIA_MOUNTED"/>                <action android:name="android.intent.action.MEDIA_REMOVED"/>                <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>                <data android:scheme="file"/>            </intent-filter>        </receiver>
public class SDReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        //判断收到的是神马广播        //获取广播中的action        String action = intent.getAction();        if(Intent.ACTION_MEDIA_MOUNTED.equals(action)){            Toast.makeText(context, "sd卡就绪", 0).show();        }        else if(Intent.ACTION_MEDIA_REMOVED.equals(action)){            Toast.makeText(context, "sd卡被拔出了", 0).show();        }        else if(Intent.ACTION_MEDIA_UNMOUNTED.equals(action)){            Toast.makeText(context, "sd卡被卸载了", 0).show();        }    }}

参考:Android BroadcastReceiver

原创粉丝点击