android 动态静态广播注册

静态广播注册(及时activity已经被销毁广播正常运作)

  

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.administrator.myapplication">
  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
        <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <receiver android:name=".MyReceiver">
        <intent-filter>
          <action android:name="com.runbo.sos.key.down"/>
        </intent-filter>
      </receiver>
  </application>
</manifest>


选中的部分为静态广播的注册
此广播是业务需求 其他设备没有
MyReceiver 为注册广播接受的模块


public class MyReceiver extends BroadcastReceiver {    
  private static final String TAG = "MyReceiver";
  public MyReceiver(){
    Log.i(TAG,"MyReceiver constructor");
  }
  @Override   
  public void onReceive(Context context, Intent intent) {
Log.i(TAG,"onReceive start");
Toast.makeText(context,"广播监听到了",Toast.LENGTH_SHORT);
Log.i(TAG,"onReceive end"+context);
}
}
动态广播注册

生命广播接受的对象
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
  package="com.example.administrator.myapplication">    
  <application        
    android:allowBackup="true"        
    android:icon="@mipmap/ic_launcher"        
    android:label="@string/app_name"        
    android:roundIcon="@mipmap/ic_launcher_round"       
    android:supportsRtl="true"        
    android:theme="@style/AppTheme">        
      <activity android:name=".MainActivity">           
        <intent-filter>                
          <action android:name="android.intent.action.MAIN" />                
          <category android:name="android.intent.category.LAUNCHER" />            
         </intent-filter>        
      </activity>        
      <receiver android:name=".MyReceiver">           
         
      </receiver>    
  </application>
</manifest>


完成动态广播的注册
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String SOS_KEY ="com.runbo.sos.key.down";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"onCreate start");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter(SOS_KEY);
registerReceiver(myReceiver,filter);
Log.i(TAG,"onCreate end");
}
}
其他广播的监听有的需要申请权限 
有的只能进行动态注册 比如亮屏 灭屏幕
原文地址:https://www.cnblogs.com/NISUN/p/9429222.html