Android_Broadcast

静态和动态两种注册方法:

  • 静态注册, 在AndroidManifest.xml中加上标签。
  • 动态注册, 通过 Context.registerReceiver()方法进行注册。比如在onResume中注册,在onPause中注销。
public class MyReceiver extends BroadcastReceiver{ 
public MyReceiver() { 
super(); 
Log.d(AppConstants.LOG_TAG, "Receiver constructor"); 
} 
@Override 
public void onReceive(Context context, Intent intent) {        
Log.d(AppConstants.LOG_TAG, "onReceive"); 
String message = intent.getStringExtra("msg");    
Log.i(AppConstants.LOG_TAG, message);  
Toast.makeText(context, "Received! msg: " + message, Toast.LENGTH_SHORT).show(); 
}
}

发送广播

public static final String BROADCAST_ACTION ="com.example.demobroadcast.BroadcastAction";
Intent intent = new Intent();     
intent.setAction(BROADCAST_ACTION);   
intent.putExtra("msg", "发送广播"); 
sendBroadcast(intent);

动态注册

@Override protected void onResume() { 
super.onResume(); 
mReceiver = new MyReceiver(); 
IntentFilter intentFilter= new   
IntentFilter(BROADCAST_ACTION); registerReceiver(mReceiver,  
intentFilter); 
} 
@Override protected void onPause() { 
super.onPause(); 
unregisterReceiver(mReceiver); 
}

静态注册


        
            
        
    

你可能感兴趣的:(Android_Broadcast)