在Manifest中注册广播接收器以及接受广播的类型,并通过Activity中的按钮发出广播,通过接收器接受并响应。
?
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.xmlbroadcast" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 注册广播监听器 --> <receiver android:name="TestReceiver"> <intent-filter> <!-- 注明接受广播的类型 --> <action android:name="android.intent.action.EDIT"/> </intent-filter> </receiver> </application></manifest>
?
TestReceiver类,用来注明接受响应后执行的操作。
package com.example.xmlbroadcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class TestReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub //Toast to1=null; //to1.makeText(null,"fuck", Toast.LENGTH_SHORT); //to1.show(); System.out.print("ReceiveMessage"); //TextView tx1=null; //tx1=(TextView)findViewById(R.id.txv); }}?
通过Activity中的按钮发出一个广播
package com.example.xmlbroadcast;import java.io.*;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity { private TextView tx1=null; private Button bt1=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt1=(Button)findViewById(R.id.btn); bt1.setOnClickListener(new bt1listener()); tx1=(TextView)findViewById(R.id.txv); } class bt1listener implements OnClickListener{ public void onClick(View v) { // TODO Auto-generated method stub System.out.print("fuck"); tx1.setText("fuck"); Intent it1=new Intent(); it1.setAction(Intent.ACTION_EDIT); MainActivity.this.sendBroadcast(it1); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; }}?
?