(不推荐)
可以通过代码完成广播的注册
在main.xml中:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center_horizontal">
<Button
android:id="@+id/mybut"
android:layout_marginTop="8dp"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#ffffff"
android:background="#3399ff"
android:text="开始广播"/>
</LinearLayout>
新建MyBroadCastReceviceUtil.java:
package com.li.broadcastproject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiverUtil extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("org.lxh.action.LYW".equals(intent.getAction())) { // 指定的Action
String msg = intent.getStringExtra("msg") ; // 取得附加信息
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
}
在MyBroadcastDemo.java中:
package com.li.broadcastproject;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyBroadcastDemo extends Activity {
private Button mybut = null ;
private MyBroadcastReceiverUtil broadUtil = null ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.mybut = (Button) super.findViewById(R.id.mybut);
this.mybut.setOnClickListener(new OnClickListenerImpl()) ;
}
private class OnClickListenerImpl implements OnClickListener{
public void onClick(View v) {
Intent it = new Intent("org.lxh.action.LYW"); // 操作的过滤
it.putExtra("msg", "Hello 李叶文") ; // 附加信息
IntentFilter filter = new IntentFilter("org.lxh.action.LYW") ;
MyBroadcastDemo.this.broadUtil = new MyBroadcastReceiverUtil() ;
MyBroadcastDemo.this.registerReceiver(MyBroadcastDemo.this.broadUtil, filter) ;
MyBroadcastDemo.this.sendBroadcast(it) ;
}
}
}