|
在Android中,广播(broadcast)是非常有用的功能。通过广播可以通知其他广播接受这某个事件发生了。比如电源不足,信号不好等。
下面我做了一个简单的demo,首先看看activity- package com.android.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()发送一个广播。
我们再看看广播接收者代码:
- package com.android.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
- <? 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 >
|
在receiver的action中定义了该receiver能够接受的广播。
----------------------------
原文链接:https://blog.51cto.com/buaadallas/377637
程序猿的技术大观园:www.javathinker.net
[这个贴子最后由 flybird 在 2020-04-14 08:30:02 重新编辑]
|
网站系统异常
系统异常信息 |
Request URL:
http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=3057
java.lang.NullPointerException
如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员。
|
|