首页 > 系统 > Android > 正文

42.android广播-自定义广播

2019-11-09 15:25:45
字体:
来源:转载
供稿:网友

自定义广播和系统广播不一样的是,action是自定义的自己随便定义,在清单文件中体现,这个在现实中用的很少,大部分都是接受系统广播。

代码示例

app1:发送广播(专门发广播)

activity_main.xml

<RelativeLayout 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"    tools:context=".MainActivity" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="发送自定义广播"         android:onClick="click"        /></RelativeLayout>MainActivity.java

package com.ldw.selfbroadcast;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {    @Override    PRotected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void click(View v){    	//发送自定义广播    	Intent intent = new Intent();    	//广播中的action是自定义的    	intent.setAction("com.ldw.self");    	sendBroadcast(intent);    }    }app2:接受自定义广播(接受广播)

清单文件需要添加的配置

        <receiver android:name="com.ldw.receiveself.selfReceiver">            <intent-filter>                <action android:name="com.ldw.self"/>            </intent-filter>        </receiver>selfReceiver.java

package com.ldw.receiveself;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class selfReceiver extends BroadcastReceiver {	@Override	public void onReceive(Context context, Intent intent) {		// TODO Auto-generated method stub		System.out.println("自定义广播");	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表