2KB项目,专业的源码交易网站 帮助 收藏 每日签到

Android 发送和接收自定义广播

  • 时间:2019-01-23 18:39 编辑:2KB 来源:2KB.COM 阅读:403
  • 扫一扫,手机访问
  • 分享
摘要:
Android 英文原文:Android | Sending & Receiving Custom Broadcasts

android系统会发送许多系统级别的广播,比如屏幕关闭,电池电量低等广播。同样应用可以发起自定义“由开发者定义的”广播。广播是从一个应用内部向另一个应用发送消息的途径之一。

BroadcastReceiver是一个可以监听和响应广播的组件。本文中,我们将会演示如何发送自定义广播以及如何通过编程和使用Manifest文件定义一个BroadcastReceiver来监听这一广播。

目标:

  • 如何发送广播
  • 如何创建一个broadcast receiver
  • 如何在Java代码中清单文件注册接收

环境与工具

  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “模拟器”
  • Min SDK 8

( 1 )创建布局UI

  • res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="Received Broadcasts" />
    <Button 
        android:id="@+id/btnSendBroadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="Send Broadcast"
        />
    <EditText
        android:id="@+id/etReceivedBroadcast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

</LinearLayout>

( 2 ) 扩展 BroadcastReceiver

  • 创建一个叫做MyReceiver的对象,继承BroadcastReceiver.
  • 重写 onReceive() 方法,在EditText中打印intent的活动名称.
  • /src/com/hmkcode/android/MyReceiver.java
package com.hmkcode.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
         MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;
         mainActivity.etReceivedBroadcast.append("broadcast: "+intent.getAction()+"
");
	}
	
}

( 3 ) 发送广播

  • 发送广播创建一个包含活动名称的Intent,将它传递给sendBroadcast()。
Intent i = new Intent("com.hmkcode.android.USER_ACTION");
sendBroadcast(i);

( 4 ) 通过Java或XML方式注册BroadcastReceiver

你可以通过java代码动态注册或在Manifest xml文件中进行注册。

  • 使用Java代码

  • 创建BroadcastReceiver类的实例MyReceiverIntentFilter实例并将他们传递给registerReceiver()方法
@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(new MyReceiver(), 
         new IntentFilter("com.hmkcode.android.USER_ACTION"));

    }
  • 在Manifest XML 文件中配置

  • 另外你可以在manifest文件中注册接收器
 <receiver android:name="com.hmkcode.android.MyReceiver" >
	<intent-filter>
	    <action android:name="com.hmkcode.android.USER_ACTION" />
	</intent-filter>
</receiver>

( 5 ) Activity Class

  • /src/com/hmkcode/android/MainActivity.java
package com.hmkcode.android;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity implements OnClickListener {

    MyReceiver myReceiver;
    IntentFilter intentFilter;
    EditText etReceivedBroadcast;
    Button btnSendBroadcast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
        btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
        
        //keep reference to Activity context
        MyApplication myApplication = (MyApplication) this.getApplicationContext();
        myApplication.mainActivity = this;

        btnSendBroadcast.setOnClickListener(this);
        
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter("com.hmkcode.android.USER_ACTION");
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myReceiver, intentFilter);

    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myReceiver);
    }
    
    
    @Override
    public void onClick(View view) {
        
        Intent intnet = new Intent("com.hmkcode.android.USER_ACTION");
        sendBroadcast(intnet);
    
    }
    
}

( 6 ) Manifest.XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hmkcode.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:name="com.hmkcode.android.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.hmkcode.android.MainActivity"
            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="com.hmkcode.android.MyReceiver" >
			<intent-filter>
				<action android:name="com.hmkcode.android.USER_ACTION" />
			</intent-filter>
		</receiver>
		
    </application>

</manifest>

注:如果你想通过Manifest XML文件注册接收器,那么需要从MainActivity类中移除onResumeonPause方法。

( 7 ) 获取Activity Context 的办法

当使用xml注册接收器时,系统将ReceiverResctrictredContext传递给onReceive()方法。为了能在EditText中进行打印,需要获取MainActivity context,因此需要通过扩展Application来持有MainActivity的引用。

package com.hmkcode.android;

import android.app.Application;

public class MyApplication extends Application {

	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	MainActivity mainActivity;
	
}

注意:我们在Manifest文件中使用了MyApplication。

<application
        android:name="com.hmkcode.android.MyApplication"
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。 2KB翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。


2KB项目(www.2kb.com,源码交易平台),提供担保交易、源码交易、虚拟商品、在家创业、在线创业、任务交易、网站设计、软件设计、网络兼职、站长交易、域名交易、链接买卖、网站交易、广告买卖、站长培训、建站美工等服务

  • 全部评论(0)
资讯详情页最新发布上方横幅
最新发布的资讯信息
【计算机/互联网|】Nginx出现502错误(2020-01-20 21:02)
【计算机/互联网|】网站运营全智能软手V0.1版发布(2020-01-20 12:16)
【计算机/互联网|】淘宝这是怎么了?(2020-01-19 19:15)
【行业动态|】谷歌关闭小米智能摄像头,因为窃听器显示了陌生人家中的照片(2020-01-15 09:42)
【行业动态|】据报道谷歌新闻终止了数字杂志,退还主动订阅(2020-01-15 09:39)
【行业动态|】康佳将OLED电视带到美国与LG和索尼竞争(2020-01-15 09:38)
【行业动态|】2020年最佳AV接收机(2020-01-15 09:35)
【行业动态|】2020年最佳流媒体设备:Roku,Apple TV,Firebar,Chromecast等(2020-01-15 09:31)
【行业动态|】CES 2020预览:更多的流媒体服务和订阅即将到来(2020-01-08 21:41)
【行业动态|】从埃隆·马斯克到杰夫·贝佐斯,这30位人物定义了2010年代(2020-01-01 15:14)
联系我们

Q Q: 7090832

电话:400-0011-990

邮箱:7090832@qq.com

时间:9:00-23:00

联系客服
商家入住 服务咨询 投拆建议 联系客服
0577-67068160
手机版

扫一扫进手机版
返回顶部