首页 > 移动平台 > 详细

Android之BroadcastReceiver1

时间:2014-04-07 22:51:14      阅读:670      评论:0      收藏:0      [点我收藏+]

1.触发发送广播

bubuko.com,布布扣
public class MainActivity extends Activity {
    private Button sendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new BroadcastListener());
        /*
         * if (savedInstanceState == null) {
         * getSupportFragmentManager().beginTransaction() .add(R.id.container,
         * new PlaceholderFragment()).commit(); }
         */
    }

    class BroadcastListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            TestReceiver tr = new TestReceiver();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_EDIT);
            MainActivity.this.sendBroadcast(intent);
        }
    }
bubuko.com,布布扣

 

2.注册广播

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mars_1700_broadcast"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mars_1700_broadcast.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=".TestReceiver">
            <intent-filter>
                <action android:name="android.intent.action.EDIT"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
bubuko.com,布布扣

 

3.定义接收广播类

bubuko.com,布布扣
package com.example.mars_1700_broadcast;

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

public class TestReceiver extends BroadcastReceiver{

    public TestReceiver(){
        System.out.println("TestReceiver");
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("onReceive");
    }

}
bubuko.com,布布扣

 

Android之BroadcastReceiver1,布布扣,bubuko.com

Android之BroadcastReceiver1

原文:http://www.cnblogs.com/zhuawang/p/3649971.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!