欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android BroadcastReceiver常见监听整理

程序员文章站 2024-03-03 21:49:25
         在android开发应用过程中 android broadcastrece...

         在android开发应用过程中 android broadcastreceiver经常会用到,所以抽时间整理了一番,省的后续在用到的时候再去百度。

broadcastreceiver几种常见监听

1.broadcastreceiver监听拨号

<intent-filter android:priority="1000" >
       <action android:name="android.intent.action.new_outgoing_call" />
</intent-filter>
 

@override
  public void onreceive(context context, intent intent) {
    //获取拨打电话的号码
    string call=getresultdata();
    //在电话号码前加上110,然后返回数据
    setresultdata("110"+call);
  } 

 2.broadcastreceiver监听短信

<receiver android:name="smsreceiver">
     <intent-filter android:priority="1000">
        <action android:name="android.provider.telephony.sms_received"></action>
     </intent-filter>
</receiver>
 

3.broadcastreceiver监听sd卡状态

<receiver android:name=".sdstatusreceiver">
   <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 sdstatusreceiver extends broadcastreceiver { 
  
  @override 
  public void onreceive(context context, intent intent) { 
    //判断收到的到底是什么广播 
    string action = intent.getaction(); 
    if("android.intent.action.media_mounted".equals(action)){ 
      toast.maketext(context, "sd卡可用", 0).show(); 
    } 
    else if("android.intent.action.media_removed".equals(action)){ 
      toast.maketext(context, "sd卡拔出", 0).show(); 
    } 
    else if("android.intent.action.media_unmounted".equals(action)){ 
      toast.maketext(context, "sd卡不可用", 0).show(); 
    } 
  } 
} 
  

4.broadcastreceiver监听开机

<receiver android:name="bootcompeletedreceiver">
      <intent-filter >
        <action android:name="android.intent.action.boot_completed"/>
      </intent-filter>
</receiver>
 

5.broadcastreceiver监听应用安装卸载

<receiver android:name="intallreceiver">
      <intent-filter >
        <action android:name="android.intent.action.package_removed"/>
        <action android:name="android.intent.action.package_added"/>
        <data android:scheme="package"></data>
      </intent-filter>
</receiver>
public class intallreceiver extends broadcastreceiver {<br>
  @override
  public void onreceive(context context, intent intent) {
    string packagename = intent.getdata().tostring();
    string action = intent.getaction();
    // 如果是卸载
    if ("android.intent.action.package_removed".equals(action)) {
        toast.maketext(context, packagename+"应用程序被卸载", 1).show();
        system.out.println(packagename+"已删除");
    } else if ("android.intent.action.package_added".equals(action)) {
        toast.maketext(context, packagename+"应用程序安装", 1).show();
        system.out.println(packagename + "已安装");
    }
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!