永发信息网

利用广播在activity之间传递数据

答案:2  悬赏:0  手机版
解决时间 2021-02-19 00:36
  • 提问者网友:兔牙战士
  • 2021-02-18 12:55
我想利用广播在activity之间传递数据(不是直接使用Intent传递Bundle),从MainActivity点击按钮跳转到SecondActivy并发送一条广播,但广播接收不到,请问是哪里的问题,谢谢!

MainActivity:

public class MainActivity extends Activity{
private Button mButton;

@override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button);

mButton.setOnClickListenner(new OnClickListener(){
@override
public void onClick(View v){
startActivity(new Intent(MainActivity.this, SecondActivity.class));

Intent broadIntent = new Intent("com.example.broadcasttest");
broadIntent.putExtra("position", 3);

sendBroadcast(broadIntent);
}
});
}
}

SecondActivity:

public class SecondActivity extends Activity{
private int position;

@override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

IntenFilter filter = new IntenFilter("com.example.broadcasttest");
registerReceiver(receiver, filter);
}

BroadcastReceiver receiver = new BroadcastReceiver(){
@override
public void OnReceive(Context context, Intent intent){
position = intent.getIntExtra("position", 0);
Log.e("","position-->"+position);
}
}

@override
protected void onDestroy(){
super.OnDestroy();
unRegisterReceiver(receiver);
}
}

将startActivity(new Intent(MainActivity.this, SecondActivity.class));放在sendBroadcast(broadIntent);的后面还是收不到。
最佳答案
  • 五星知识达人网友:封刀令
  • 2021-02-18 14:21
startActivity(new Intent(MainActivity.this, SecondActivity.class));
startActivity是一个异步的过程,代码不会等待执行完再接着往下执行。所以second收不到
Intent broadIntent = new Intent("com.example.broadcasttest");
broadIntent.putExtra("position", 3);

sendBroadcast(broadIntent);
全部回答
  • 1楼网友:冷風如刀
  • 2021-02-18 14:56
class abc: public class abc implements serializable{ private string name; public string getname() { return name; } public void setname(string name) { this.name = name; } } activity1传值: abc abc1 = new abc(); abc1.setname("abc1"); abc abc2 = new abc(); abc2.setname("abc2"); arraylist abclist = new arraylist(); abclist.add(abc1); abclist.add(abc2); intent intent = new intent(); intent.putextra("abclist", abclist); intent.setclass(activity1.this, activity2.class); startactivity(intent); activity2取值: arraylist abclist = (arraylist) getintent().getserializableextra("abclist"); system.out.println(abclist.get(0).getname()); system.out.println(abclist.get(1).getname());
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯