思路
Activity向广播接收器传递数据很简单,只需要在发送广播前将数据put进Intent中就行了。
广播接收器怎么向Activity传送数据?这里要用到接口,通过在广播接收器里定义一个接口,然后让接收广播接收器数据的Activity实现这个接口。先看下面的栗子,Activity发送一个广播,然后广播接收器返回一个字符串。
具体案例
Activity 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.nangch.broadcastreceivertest.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送广播"/>
</LinearLayout>
Activity代码
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements MyReceiver.Message{
TextView tv;
MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册广播接收器
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.nangch.broadcasereceiver.MYRECEIVER");
registerReceiver(myReceiver, intentFilter);
//因为这里需要注入Message,所以不能在AndroidManifest文件中静态注册广播接收器
myReceiver.setMessage(this);
tv = (TextView) findViewById(R.id.tv);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.nangch.broadcasereceiver.MYRECEIVER");
intent.putExtra("hello", tv.getText()); //向广播接收器传递数据
sendBroadcast(intent); //发送广播
}
});
}
@Override
public void getMsg(String str) {
//通过实现MyReceiver.Message接口可以在这里对MyReceiver中的数据进行处理
tv.append(str);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver); //注销广播接收器
}
}
广播接收器代码
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private Message message;
@Override
public void onReceive(Context context, Intent intent) {
//接收MainActivity传过来的数据
Toast.makeText(context, intent.getStringExtra("hello"), Toast.LENGTH_SHORT).show();
//调用Message接口的方法
message.getMsg(" world");
}
interface Message {
public void getMsg(String str);
}
public void setMessage(Message message) {
this.message = message;
}
}
在 MyReceiver 中定义一个 Message 接口,并声明一个 Message 类型的成员变量 message。然后让 MainActivity实现这个接口,并调用 setMessage 方法将 MainActivity 注入,这样 MainActivity 实例就成了 Myreceiver 的成员变量 message,这样就能处理 MyReceiver 中的数据了。这种思想和我们学习 Android 时设置按钮监听器的思想差不多,仔细想一下还是很好理解的。
引用
本文转载自 https://www.cnblogs.com/nangch/p/5353563.html ,感谢原作者的整理。