[Android]自定义广播之标准广播

来源:互联网 发布:莫寒应援会的淘宝店 编辑:程序博客网 时间:2024/05/22 15:54

自定义广播允许开发人员在应用程序内进行发送自己定义的广播。
1、新建MyBroadcastReceiver类,继承于BroadcastReceiver,在onReceive方法中,接收到广播内容。

package com.example.broadcasttest1;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadcastReceiver extends  BroadcastReceiver{    @Override    public void onReceive(Context arg0, Intent arg1) {        // TODO Auto-generated method stub        Toast.makeText(arg0, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();    }}

2、在activity_main.xml中,新建一个按钮。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Broadcase" /></LinearLayout>

3、在MainActivity中,点击按钮事件中发送一条自定义广播

package com.example.broadcasttest1;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.content.Intent;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.os.Build;public class MainActivity extends ActionBarActivity {    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button)findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                Intent intent = new Intent("com.example.broadcasttest1.**MY_BROADCAST**");                // 发送广播信息                sendBroadcast(intent);            }        });    }}

4、最后在AndroidManifest.xml 中,对广播接收器进行注册。

<receiver android:name=".MyBroadcastReceiver">            <intent-filter>                <action android:name="com.example.broadcasttest1.**MY_BROADCAST**"/>            </intent-filter>        </receiver>

点击按钮,我们可以看到界面弹出一条信息:“received in MyBroadcastReceiver”。说明我们发送的自定义消息已经发送并且被收到。

0 0