Android自定义广播接收
作者:Lssの老父亲
这篇文章主要为大家详细介绍了Android自定义广播接收,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Android自定义广播接收的具体代码,供大家参考,具体内容如下
实现效果:
MainActivity.java代码:
package com.henu.broadcastsample; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private MyBroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View v) { //动态注册广播接收 receiver = new MyBroadcastReceiver(); String action = "henurjxy"; IntentFilter intentFilter=new IntentFilter(action); registerReceiver(receiver,intentFilter); Intent intend = new Intent("henurjxy"); sendBroadcast(intend); } //在页面销毁时,注销广播接收者 @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } }
MyBroadcastReceiver.java代码:
package com.henu.broadcastsample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { public MyBroadcastReceiver(){} @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"是我发出的广播哦",Toast.LENGTH_SHORT).show(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。