为什么此广播接收器适用于Android?

时间:2018-05-09 19:12:48

标签: android broadcastreceiver manifest

我是Android编程的初学者,现在我正坐在这个问题的前面:我会编写一个广播接收器,每当电话被充电或“放电”时就会被解雇。因此,在Manifest.xml中注册了Receiver:

<receiver
   android:name=".Starter"
   android:enabled="true"
   android:exported="true">
   <intent-filter>
      <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
      <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
   </intent-filter>
</receiver>

在广播接收器的类中,我在onReceive() - 方法中写了一个Toast,当接收器工作时,应该执行该方法:

>     public class Starter extends BroadcastReceiver {
>     
>         @Override
>         public void onReceive(Context context, Intent intent) {
>             Toast.makeText(context,"blablabla",Toast.LENGTH_LONG).show();
>         }
>     }

我非常感谢每一次帮助,LG

1 个答案:

答案 0 :(得分:0)

使用BroadcastReceiver时,必须在将侦听广播的类中注册。

这是使用Context.registerReceiver()$http

完成的

LocalBroadcastManager.getInstance(...).registerReceiver(...)https://developer.android.com/reference/android/content/Context#registerreceiver)。

  1. 创建将监听特定广播的IntentFilter

  2. onResume()扩展ActivityFragment的类中注册您的接收者。

    class MainActivity extends Activity 
    {
        Starter myReceiver = new Starter(); // This is your class that extends BroadcastReceiver
    
        @Override
        public void onResume()
        {
            super.onResume();
    
            // Create IntentFilters that will listen for certain actions:
            IntentFilter intentFilterConnected = new IntentFilter(Intent.ACTION_POWER_CONNECTED);
            IntentFilter intentFilterDisconnected = new IntentFilter(Intent.ACTION_POWER_DISCONNECTED);
    
            // Then pass these intents to registerReceiver():
            registerReceiver(myReceiver, intentFilterConnected);
            registerReceiver(myReceiver, intentFilterDisconnected);
        }
    }
    
  3. 现在,当MainActivity收到与onReceive()匹配的广播时,myReceiver的IntentFilter将会执行。

    注意:如果实例化myReceiver的类未扩展ActivityFragment,则您需要使用LocalBroadcastManager.getInstance(...).registerReceiver(...)