运行效果
string.xml
TestBroadcast 请输入发送参数 发送广播 Settings
activity_main.xml
MainActivity
package com.mytest.testbroadcast;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity { private EditText paramText; private TextView resultView; private final String ACTION_INTENT_TEST="com.mytest.testbroad.intent"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); paramText = (EditText) this.findViewById(R.id.param_input); resultView = (TextView) this.findViewById(R.id.view_result); } /** * 发送广播按钮onclick事件 * @param view */ public void SendBroadCast(View view){ String param = paramText.getText().toString(); //创建发送intent Intent intent = new Intent(this.ACTION_INTENT_TEST); //绑定参数 intent.putExtra("user_input", param); //发送广播 this.sendBroadcast(intent); resultView.setText("发送广播成功,参数值为:"+param); } }
创建广播接听对象
package com.mytest.testbroadcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String user_input = intent.getStringExtra("user_input"); Toast.makeText(context,"接收到广播,得到参数值为"+user_input,Toast.LENGTH_SHORT).show(); }}
AndroidMainfest.xml
案例实现小结:
1、定义ACTION,并建立发送Intent,调用sendBroadcast方法发送广播;2、创建广播接收类。类要继承BroadcastReceiver,并重写onReceive方法; 3、在AndroidManifest.xml中注册广播接收对象,在intent-filter中添加ACTION。