標籤:android
一丶 broadcast receiver 廣播接收者
註:android的四大組件:
*activity使用者互動的介面
*content provider 暴露應用程式隱私的資料給別的應用程式
* broadcast receiver 廣播接收者
* service 背景服務
>Android手機裡面的廣播接受者
>系統電量不足,電池充滿,插上充電器,sd卡被拔出,sd卡插上,已撥電話,接收到了簡訊,開機完畢,螢幕鎖定,螢幕解鎖
>在Android作業系統裡面有很多的系統事件,Google工程師希望把這個事件告訴程式員(Android系統內部內建了電台),程式員註冊收音機就可以擷取對應的事件
例如1:監聽使用者撥出的電話,擷取撥出電話的廣播事件(資訊清單檔裡面配置)
買個收音機
寫個類繼承BroadcastReceiver
OutCallReceiver extends BroadcastReceiver
2. 買個電池
<receiver android:name="com.xunfang.ipdail.OutCallReceiver" >
</receiver>
3. 調整到合適的頻道
<intent-filter >
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
例如2:簡訊檢測廣播
//拿到使用者接收的所有簡訊
Object[] objs = (Object[]) intent.getExtras().get("pdus");
//迴圈拿到簡訊
for (Object obj : objs) {
SmsMessage sms = SmsMessage.createFromPdu((byte[])obj) ;
//拿到簡訊的內容
String body = sms.getMessageBody() ;
//拿到簡訊的地址
String address = sms.getOriginatingAddress() ;
//拿到簡訊的發送時間
long date = sms.getTimestampMillis() ;
String d = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss").format(new Date(date)) ;
System.out.println("內容:" + body );
System.out.println("地址:" + address );
System.out.println("時間:" + d );
}
清單裡面配置合適的頻道:
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
例3:sd卡狀態監聽器
//拿到動作
String action = intent.getAction() ;
if("android.intent.action.MEDIA_MOUNTED".equals(action)){
System.out.println("sd卡裝上了,可以使用了");
Toast.makeText(context, "sd卡安裝了", 0).show() ;
}else if("android.intent.action.MEDIA_REMOVED".equals(action)){
System.out.println("sd被拔掉了,不要拔它");
Toast.makeText(context, "sd被拔掉了,不要拔它", 0).show() ;
}else if("android.intent.action.MEDIA_UNMOUNTED".equals(action)){
System.out.println("sd被卸載了,沒事不要卸載它");
Toast.makeText(context, "sd被卸載了,沒事不要卸載它", 0).show() ;
}
清單配置:
<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>
例4:應用程式的卸載和安裝監聽
//拿到動作
String action = intent.getAction() ;
System.out.println(action);
if("android.intent.action.PACKAGE_ADDED".equals(action)){
System.out.println("應用程式安裝了");
Toast.makeText(context, "應用程式安裝了", 0).show() ;
}else if("android.intent.action.PACKAGE_REMOVED".equals(action)){
System.out.println("應用程式卸載了");
Toast.makeText(context, "應用程式卸載了", 0).show() ;
}else if("android.intent.action.PACKAGE_REPLACED".equals(action)){
System.out.println("應用程式覆蓋安裝了");
Toast.makeText(context, "應用程式覆蓋安裝了", 0).show() ;
}
清單裡面的頻道配置:
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package"/>
</intent-filter>
本文出自 “android筆記” 部落格,請務必保留此出處http://2585211.blog.51cto.com/10044233/1665711
android廣播的應用