发送和接收广播

布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.Test.MainActivity"
    tools:ignore="MergeRootFrame" >


    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:text="广播" />
 

</LinearLayout>


完整代码:

public class MainActivity extends Activity {
   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.bt);//获取按钮
    button.setOnClickListener(new View.OnClickListener() {//设置单击事件

@Override
public void onClick(View v) {
Intent intent = new Intent();//创建Intent对象
intent.setAction("com.mingrisoft");//为Intent添加动作com.mingrisoft
sendBroadcast(intent);//发送广播

}
});
        
}


}



设置接收器:

public class MyReceiver extends BroadcastReceiver{

private static final String action1="com.mingrisoft";//声明第一个动作
private static final String action2="mingrisoft";//声明第二个动作


@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(action1)) {
Toast.makeText(context, "MyReceiver收到com.mingrisoft广播", Toast.LENGTH_SHORT).show();//回复收到广播
}else if (intent.getAction().equals(action2)) {
Toast.makeText(context, "MyReceiver收到mingrisoft广播", Toast.LENGTH_SHORT).show();
}

}


}


重要点:在AndroidManifest.xml文件中注册BroadcastReceiver

发送和接收广播