註冊廣播

動態註冊:

detectionSDkBroadcastReceiver = new DetectionSDkBroadcastReceiver();

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);

intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);

intentFilter.addDataScheme("file");//檢測sd卡的時候必須加上

this.registerReceiver(detectionSDkBroadcastReceiver,intentFilter);

這裏的Action 並不用在xml中註冊

靜態註冊,androidmanifest.xml文件中設置

 <receiver android:name = ".SdkBroadcastReceiver">

     <intent-filter android:priority = "1000">

    

     

    <action android:name = "android.intent.action.MEDIA_EJECT"></action>

  

      <action android:name = "android.intent.action.MEDIA_MOUNTED"></action>

   

 

      <data android:scheme = "file"></data>

     </intent-filter>

     </receiver>

代碼:建立一個接受類繼承BroadcastReceiver

覆蓋onReceive方法

public void onReceive(Context context, Intent intent) {

if(intent.getAction().equals("android.intent.action.MEDIA_EJECT"))

}

else if(intent.getAction().equals("android.intent.action.MEDIA_MOUNTED")){

 Toast.makeText(context,"MEDIA_MOUNTED", Toast.LENGTH_LONG).show();  

}

在廣播中跳轉到一個activity

Intent newIntent = new Intent();

    newIntent.setClass(context, SDkActivity.class);

newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//在廣播中進行跳轉到一個activity或者service是都必須加這一句

context.startActivity(newIntent);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章