Android学习笔记BroadcastReceiver(广播接收者)

Android发送广播的过程

Android学习笔记BroadcastReceiver(广播接收者)

代码实现

MainActivity.java

import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.btn_Broadcast);//获取广播按钮 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction("马云"); //为Itent添加动作zuckerg sendBroadcast(intent);//发送广播 } }); } }

MyReceiver.java

import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { private static final String ACTIONI = "马云";//动作1 private static final String ACTION2 = "小腾腾"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(ACTIONI)){//回复第一个广播 Toast.makeText(context, "MyReceiver收到:马云的广播", Toast.LENGTH_SHORT).show(); }else if(intent.getAction().equals(ACTION2)){//回复第二个广播 Toast.makeText(context,"MyReceiver收到:小腾腾的广播", Toast.LENGTH_SHORT). show(); } } }

AndroidManifest.xml清单文件注册BroadcastReceiver

<!-- 注册广播接收器 android:enabled="true"可以被实例化 android:exported="true"能接收其他app的广播 --> <receiver android:name=".MyReceiver" android:enabled="true" android:exported="true" tools:ignore="WrongManifestParent"> <intent-filter> <!--配置允许接收的Action--> <action android:name="马云"/> <action android:name="小腾腾"/> </intent-filter> </receiver> </application>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpsgfd.html