01_21_广播机制(一)
-
//TestActivity.java
-
package mars.testbc;
-
-
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 TestActivity extends Activity {
-
/** Called when the activity is first created. */
-
private Button sendButton;
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.testreceiver);
-
sendButton = (Button)findViewById(R.id.sendButton);
-
sendButton.setOnClickListener(new BroadcastListener());
-
}
-
/*发送广播
-
* 1、创建一个Intent对象:intent = new Intent
-
* 2、设置广播动作intent.setAction(ITent.ACTION_EDIT)
-
* 3、发送广播:TestActivity.this.sendBroadcast(intent)*/
-
class BroadcastListener implements OnClickListener{
-
-
@Override
-
public void onClick(View v) {
-
System.out.println("Click --- button ");
-
Intent intent = new Intent();
-
intent.setAction(Intent.ACTION_EDIT);
-
TestActivity.this.sendBroadcast(intent);
-
}
-
/*注意:上面的intent.setAction(Intent.ACTION_EDIT);和
-
* AndroidMainfext.xml中的是对应的
-
-
-
-
-
*/
-
}
-
}
-
//TestReceiver.java
-
package mars.testbc;
-
-
import android.content.BroadcastReceiver;
-
import android.content.Context;
-
import android.content.Intent;
-
-
/*TestReceiver继承了BroadcastReceiver并复写了onReceive()方法
-
*
-
* 处理广播消息*/
-
public class TestReceiver extends BroadcastReceiver{
-
-
public TestReceiver(){
-
System.out.println("TestReceiver");
-
}
-
@Override
-
public void onReceive(Context context, Intent intent) {
-
System.out.println("onReceive");
-
}
-
}
-
<?xml version="1.0" encoding="utf-8"?>
-
<manifest xmlns:android=""
-
package="mars.testbc" android:versionCode="1" android:versionName="1.0">
-
<application android:icon="@drawable/icon" android:label="@string/app_name">
-
<activity android:name=".TestActivity" 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=".TestReceiver">
-
<intent-filter>
-
<action android:name="android.intent.action.EDIT" />
-
</intent-filter>
-
</receiver>
-
</application>
-
<uses-sdk android:minSdkVersion="4" />
-
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
-
</manifest>
结果如下:(从结果可知每次广播信息均重新生成
TestReceiver并调用onReceive方法)
04-10 12:31:55.597: I/System.out(511): Click --- button
04-10 12:31:55.706: I/System.out(511): TestReceiver
04-10 12:31:55.706: I/System.out(511): onReceive
04-10 12:31:59.567: I/System.out(511): Click --- button
04-10 12:31:59.607: I/System.out(511): TestReceiver
04-10 12:31:59.607: I/System.out(511): onReceive
阅读(736) | 评论(0) | 转发(0) |