首页 > 代码库 > Android学习笔记-广播机制
Android学习笔记-广播机制
Android广播类似QT中的信号和槽~~~
界面文件activity_main.xml
<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/send1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:text="send 1" /> <Button android:id="@+id/send2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/send1" android:text="send 2" />
MainActivity.java
public class MainActivity extends Activity { public static final String ACTION_1 = "send1~~~"; public static final String ACTION_2 = "send2~~~~~~"; private BroadcastReceiver receiver; private TextView textView = null; private Button button1 = null; private Button button2 = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView1); textView.setText(""); button1 = (Button) findViewById(R.id.send1); button2 = (Button) findViewById(R.id.send2); initView(); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); String data = intent.getExtras().getString("data"); if (action.equals(ACTION_1)) { textView.setText(""); textView.setText("接收到:\n" + ACTION_1 + "\n1内容是:" + data); } else if (action.equals(ACTION_2)) { textView.setText(""); textView.setText("接收到:\n" + ACTION_2 + "\n2内容是:" + data); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_1); filter.addAction(ACTION_2); registerReceiver(receiver, filter); } public void initView() { OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.send1: Intent intent1 = new Intent(ACTION_1); intent1.putExtra("data", "action_01"); sendBroadcast(intent1); break; case R.id.send2: Intent intent2 = new Intent(ACTION_2); intent2.putExtra("data", "action_02"); sendBroadcast(intent2); break; default: break; } } }; button1.setOnClickListener(onClickListener); button2.setOnClickListener(onClickListener); } @Override protected void onStop() { super.onStop(); unregisterReceiver(receiver);//解除注册 } }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1581613
Android学习笔记-广播机制
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。