广播的发送与接收

时间:2022-12-15 16:43:05

======================发送广播======================================================================

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
 
public class Test extends Activity{
   
            public void onClick(View v) {
                Intent mIntent = new Intent("ACTION_NAME"); 
                mIntent.putExtra("yaner", "发送广播,相当于在这里传送数据");
                
                //发送广播
                sendBroadcast(mIntent);
            }
        });
    }
}

======================接收广播======================================================================

private BroadcastReceiver br;
public void onCreate(Bundle savedInstanceState)
{
 ....... 
    br = new BroadcastReceiver()
  {     
   @Override  
   public void onReceive(Context context, Intent intent)
   {
    String action= intent.getAction();

    if(action.equals("ACTION_NAME"))

   {   

    Toast.makeText(context, " 动态注册BroadcastReceiver ~~ ", Toast.LENGTH_LONG).show();  

    }
   } 
  };
 .......
}
protected void onStart()
{
 Log.i(TAG, "--->onStart  注册广播接收器"); 
 super.onStart();  //注册广播接收器(动态注册) 
 IntentFilter filter = new IntentFilter(); 
 filter.addAction("ACTION_NAME"); 
 this.registerReceiver(br, filter);

protected void onStop()

 Log.i(TAG, "--->onStop 取消注册的广播接收器"); 
 super.onStop();  //取消注册的广播接收器 
 this.unregisterReceiver(br);
}