|
在Android中,广播(broadcast)是非常有用的功能。通过广播可以通知其他广播接受这某个事件发生了。比如电源不足,信号不好等。
下面我做了一个简单的demo,首先看看activity
java代码: package eoe.broadcasttest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BroadcastTest extends Activity {
public static final String NEW_LIFEFORM_DETECTED =
"com.android.broadcasttest.NEW_LIFEFORM";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn0 = (Button)findViewById(R.id.btn0);
btn0.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent it = new Intent(NEW_LIFEFORM_DETECTED);
sendBroadcast(it);
}
});
}
}
在这个activity中生成了一个按钮,当按下按钮的时候通过sendBroadcast()发送一个广播。
我们再看看广播接收者代码:
java代码: package eoe.broadcasttest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String BURN =
"com.paad.alien.action.BURN_IT_WITH_FIRE";
public MyBroadcastReceiver () {
Log.v("BROADCAST_TAG", "myBroadCast");
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "成功接收广播:", Toast.LENGTH_LONG).show();
}
}
在onReceive()中实现了当接收到广播所做的动作。
我们还需要在AndroidManifest.xml中注册该receiver
java代码: <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package="com.android.broadcasttest"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BroadcastTest"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.android.broadcasttest.NEW_LIFEFORM" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest> |
|