静的定義receiverはbroadcast intentを受信する

2579 ワード

[ static broadcast receiver] 1. ActivityはsendBroadcast()を介してIntentデータを送信する
2.MyReceiverはbroadcastから送信されたIntentを受信し、Intentからパラメータを抽出する
[In Activity]現在のActivityクラスには、broadcast Intent用のコードクリップがあります.
Intent intent = getIntent4Broadcast();
/*the same as 
 *this.sendBroadcast(intent);*/
sendBroadcast(intent);

public Intent getIntent4Broadcast(){
  Bundle b = new Bundle();
  b.putString("arg0","data1");
  Intent intent = new Intent();
  /* Receiver will filter the term 
   * com.example.lab3.static_bc*/
  intent.setAction("com.example.lab3.static_bc");
  intent.putExtra("data", b);
  return intent;
}

[ Definite BroadcastReceiver ]
e.g. MyReceiver.JAva extends BroadcastReceiver onReceiveインタフェースの再定義
public class MyReceiver extends BroadcastReceiver{
	@Override
	public void onReceive(Context context, Intent intent){
		Bundle b = intent.getBundleExtra("data");
        // do something with b
	}
}

[Manifest.xml]静的定義BroadcastReceiver
マニフェストにReceiverを登録する必要があります

        ...
        ...
        //MyReceiver  receiver   
        
            
                
                    
            
        
        ...
        ...
    

[ dynamic broadcast receiver ]
1.ActivityでReceiverとIntentFilterを定義する
2.onCreateでbroadcastを送信し、定義されたReceiverがbroadcastを処理する
[ActivityでBroadcastReceiverを定義]
    ...
    /*definite inner class
     *       BroadcastReceiver
    */
	public BroadcastReceiver bcr = new BroadcastReceiver(){  
		@Override
        public void onReceive(Context context, Intent intent) {  
            //do something with intent  
        }
    };
    ...

[ActivityにBroadcastReceiverを登録する]
どの関数の中でregister BroadcastReceiver、またどの関数の中でunregisterですか?参考:broadcastを送信する前にregisterが既に存在することを確認します.when click app-icon onCreate()->onStart()->onResume() when click back_btn onPause()はonStop()にunregister、onCreate()およびonStart()にregisterと書くことができる.
...
private IntentFilter filter = new IntentFilter();
...
//register receiver
filter.addAction("com.example.lab3.dynamic_bc");
registerReceiver(bcr, filter);
...
//unregister receiver
unregisterReceiver(bcr);
...

[ broadcast intent ]
Intent intent = initializeTheIntentForBroadcast();
sendBroadcast(intent)