Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android Broadcast學習

Android Broadcast學習

編輯:初級開發

其實所謂的靜態注冊,動態注冊,是指接收廣播的時候,是靜態注冊接收還是動態注冊接收,發送的時候不分靜態,動態
以發送intent為例,
一共分4種情況,以每次注冊兩個Broadcast為例:
情況一,注冊2個靜態Broadcast

如果是靜態注冊的,接收的一定是某一個類繼承BroadcastReceiver

2個Java文件如下:
BroadcastActivity.Java
代碼 
package com.broad.test1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.util.Log;

//2個靜態注冊
public class BroadcastActivity extends Activity {
    /** Called when the activity is first created. */
    private Button button01;
    private Button button02;
    private static final String TAG = "BroadcastActivity";
    private static final String INTENAL_ACTION_1 = "su1.bluetooth.true";
    private static final String INTENAL_ACTION_2 = "su1.bluetooth.false";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentVIEw(R.layout.main);
        button01 = (Button) findVIEwById(R.id.button01);
        button02 = (Button) findVIEwById(R.id.button02);
        button01.setOnClickListener(mybtnListener);
        button02.setOnClickListener(mybtnListener);
    }

    private OnClickListener mybtnListener = new OnClickListener() {

        @Override
        public void onClick(VIEw v) {
            // TODO Auto-generated method stub
            if (v.getId() == (R.id.button01)) {
                Intent intent = new Intent(INTENAL_ACTION_1);
                // 也可以用mContext.sendBroadcast(intent),mContext.sendBroadcast可以在構造函數裡面初始化,
                // 有內部類的時候必須用???
                sendBroadcast(intent);
            } else if (v.getId() == (R.id.button02)) {
                Intent intent = new Intent(INTENAL_ACTION_2);
                sendBroadcast(intent);
            } else {
                Log.v(TAG, "not true not false");
            }
        }

    };

}

BroadcastRecTest.Java
代碼 
package com.broad.test1;

import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BroadcastRecTest extends BroadcastReceiver {
    private static final String TAG="BroadcastActivity";
    private static final String INTENAL_ACTION_1="su1.bluetooth.true";
    private static final String INTENAL_ACTION_2="su1.bluetooth.false";
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(action.equals(INTENAL_ACTION_1)){
            Log.d(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>>>su1.bluetooth.true");
            }else if(action.equals(INTENAL_ACTION_2)){
                Log.d(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>su1.bluetooth.false");
            }else{
                Log.d(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>other type intent");
            }

        }
}
main.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
    android:orIEntation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextVIEw  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button
    android:id="@+id/button01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="靜態接收廣播true"/>
<Button
    android:id="@+id/button02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="靜態接收廣播false"/>
</LinearLayout>
androidManifest.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<manifest XMLns:android="http://schemas.android.com/apk/res/android"
      package="com.broad.test1"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BroadcastActivity"
                  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="BroadcastRecTest">
        <intent-filter>
            <action android:name="su1.bluetooth.true" />
            <action android:name="su1.bluetooth.false" />
        </intent-filter>
    </receiver>

    </application>
    <uses-sdk android:minSdkVersion="8" />    
</manifest> 
運行結果:
注意,靜態注冊的broadcast運行有點慢:

情況2,一個靜態,一個動態注冊Broadcast

BroadcastActivity.Java
代碼 
package com.broad.test1;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.util.Log;
//1個動態,1個靜態注冊
public class BroadcastActivity extends Activity {
    /** Called when the activity is first created. */
    private Button button01;
    private Button button02;
    private static final String TAG="BroadcastActivity";
    private static final String INTENAL_ACTION_1="su2.bluetooth.true";
    private static final String INTENAL_ACTION_2="su2.bluetooth.false";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentVIEw(R.layout.main);
        button01=(Button)findVIEwById(R.id.button01);
        button02=(Button)findVIEwById(R.id.button02);
        button01.setOnClickListener(mybtnListener);
        button02.setOnClickListener(mybtnListener);
    }
    private OnClickListener mybtnListener=new OnClickListener(){

        @Override
        public void onClick(VIEw v) {
            // TODO Auto-generated method stub
            if(v.getId()==(R.id.button01)){
                Intent intent= new Intent(INTENAL_ACTION_1);
                sendBroadcast(intent);
            }else if(v.getId()==(R.id.button02)){
                Intent intent= new Intent(INTENAL_ACTION_2);
                sendBroadcast(intent);
            }else{
                Log.v(TAG,"not true not false");
            }
        }
        
    };
    
    
        // 接收動態注冊廣播的BroadcastReceiver    
    private BroadcastReceiver bcrIntenal2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
          //如果有多個動態注冊的廣播,要用if(action.equals()){}else if(action.equals()){}來判斷是哪個
            //String action = intent.getAction();
            //這裡只有一個,不用判斷了。
            Log.v(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>dong--su2.bluetooth.false");
        }
    };
    //在onStart中動態注冊廣播,當然也可以在onCreate裡面注冊
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        //動態注冊
        IntentFilter intentFilter= new IntentFilter(INTENAL_ACTION_2);
        //也可以用這種方法動態注冊多個,說明我可以”接收“這麼多的動態廣播。
       /* IntentFilter intentFilter= new IntentFilter();
        intentFilter.addAction("action1");
        intentFilter.addAction("action2");*/
        registerReceiver(bcrIntenal2,intentFilter);
    }

    //在onStop中取消注冊廣播,如果在onCreate裡面注冊,那麼在onDestroy裡面取消注冊。
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        unregisterReceiver(bcrIntenal2);
    }    
    
}
BroadcastRecTest.Java
代碼 
package com.broad.test1;

import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BroadcastRecTest extends BroadcastReceiver {
    private static final String TAG="BroadcastActivity";
    private static final String INTENAL_ACTION_1="su2.bluetooth.true";
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(action.equals(INTENAL_ACTION_1)){
            Log.d(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>>>su.bluetooth.true");
            }else{
                Log.d(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>other type intent--jingtai");
            }

        }
}
main.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
    android:orIEntation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextVIEw  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button
    android:id="@+id/button01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="靜態接收廣播true"/>
<Button
    android:id="@+id/button02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="動態接收廣播false"/>
</LinearLayout>
androidManifest.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<manifest XMLns:android="http://schemas.android.com/apk/res/android"
      package="com.broad.test1"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BroadcastActivity"
                  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="BroadcastRecTest">
        <intent-filter>
            <action android:name="su2.bluetooth.true" />
        </intent-filter>
    </receiver>

    </application>
    <uses-sdk android:minSdkVersion="8" />    
</manifest> 
true是靜態注冊的,在android.XML中注冊的,false是動態注冊的,在Java代碼中注冊的
運行結果:

情況三、兩個都是動態注冊的,在同一個Activity裡面既發送,又接收,(當然也可以在不同的java中,一個發送,另一個Java接收,哪怕是不同的包)
動態注冊不需要一個類繼承BroadcastReceiver這個類了,直接new一個對象即可
代碼 
package com.broad.test1;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.util.Log;

//兩個動態注冊
public class BroadcastActivity extends Activity {
    /** Called when the activity is first created. */
    private Button button01;
    private Button button02;
    private static final String TAG="BroadcastActivity";
    private static final String INTENAL_ACTION_1="su3.bluetooth.true";
    private static final String INTENAL_ACTION_2="su3.bluetooth.false";
   // private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentVIEw(R.layout.main);
        button01=(Button)findVIEwById(R.id.button01);
        button02=(Button)findVIEwById(R.id.button02);
        button01.setOnClickListener(mybtnListener);
        button02.setOnClickListener(mybtnListener);
    }
    private OnClickListener mybtnListener=new OnClickListener(){

        @Override
        public void onClick(VIEw v) {
            // TODO Auto-generated method stub
            if(v.getId()==(R.id.button01)){
                Intent intent= new Intent(INTENAL_ACTION_1);
                sendBroadcast(intent);
            }else if(v.getId()==(R.id.button02)){
                Intent intent= new Intent(INTENAL_ACTION_2);
                sendBroadcast(intent);
            }else{
                Log.v(TAG,"not true not false");
            }
        }
        
    };
    
        // 接收動態注冊廣播的BroadcastReceiver    
    private BroadcastReceiver bcrIntenal2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
          //如果有多個動態注冊的廣播,要用if(action.equals()){}else if(action.equals()){}來判斷是哪個
            String action = intent.getAction();
            if(action.equals(INTENAL_ACTION_1)){
                Log.v(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>dong--su3.bluetooth.true");
            }else if(action.equals(INTENAL_ACTION_2)){
                Log.v(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>dong--su3.bluetooth.false");
            }
         
        }
    };
    //在onStart中動態注冊廣播,當然也可以在onCreate裡面注冊
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        //動態注冊兩個,
        IntentFilter intentFilter= new IntentFilter();
        intentFilter.addAction(INTENAL_ACTION_1);
        intentFilter.addAction(INTENAL_ACTION_2);
        registerReceiver(bcrIntenal2,intentFilter);
    }

    //在onStop中取消注冊廣播,如果在onCreate裡面注冊,那麼在onDestroy裡面取消注冊。
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        unregisterReceiver(bcrIntenal2);
    }    
    
}
main.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
    android:orIEntation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextVIEw  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button
    android:id="@+id/button01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="動態接收廣播true"/>
<Button
    android:id="@+id/button02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="動態接收廣播false"/>
</LinearLayout>
androidManifest.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<manifest XMLns:android="http://schemas.android.com/apk/res/android"
      package="com.broad.test1"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BroadcastActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />    
</manifest> 
運行結果:

情況4,sendBroadcast的時候加權限,以2個都動態注冊為例
代碼 
package com.broad.test1;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.util.Log;

//兩個動態注冊,sendBroadcast的時候加權限
public class BroadcastActivity extends Activity {
    /** Called when the activity is first created. */
    private Button button01;
    private Button button02;
    private static final String TAG="BroadcastActivity";
    private static final String INTENAL_ACTION_1="su4.bluetooth.true";
    private static final String INTENAL_ACTION_2="su4.bluetooth.false";
     private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentVIEw(R.layout.main);
        button01=(Button)findVIEwById(R.id.button01);
        button02=(Button)findVIEwById(R.id.button02);
        button01.setOnClickListener(mybtnListener);
        button02.setOnClickListener(mybtnListener);
    }
    private OnClickListener mybtnListener=new OnClickListener(){

        @Override
        public void onClick(VIEw v) {
            // TODO Auto-generated method stub
            if(v.getId()==(R.id.button01)){
                Intent intent= new Intent(INTENAL_ACTION_1);
                sendBroadcast(intent,BLUETOOTH_PERM);
            }else if(v.getId()==(R.id.button02)){
                Intent intent= new Intent(INTENAL_ACTION_2);
                sendBroadcast(intent,BLUETOOTH_PERM);
            }else{
                Log.v(TAG,"not true not false");
            }
        }
        
    };
    
        // 接收動態注冊廣播的BroadcastReceiver    
    private BroadcastReceiver bcrIntenal2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
          //如果有多個動態注冊的廣播,要用if(action.equals()){}else if(action.equals()){}來判斷是哪個
            String action = intent.getAction();
            if(action.equals(INTENAL_ACTION_1)){
                Log.v(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>dong--su4.bluetooth.true");
            }else if(action.equals(INTENAL_ACTION_2)){
                Log.v(TAG,"surx>>>>>>>>>>>>>>>>>>>>>>>>>>>dong--su4.bluetooth.false");
            }
         
        }
    };
    //在onStart中動態注冊廣播,當然也可以在onCreate裡面注冊
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        //動態注冊兩個,說明我可以”接收“2個這樣Action的動態廣播
        IntentFilter intentFilter= new IntentFilter();
        intentFilter.addAction(INTENAL_ACTION_1);
        intentFilter.addAction(INTENAL_ACTION_2);
        registerReceiver(bcrIntenal2,intentFilter);
    }

    //在onStop中取消注冊廣播,如果在onCreate裡面注冊,那麼在onDestroy裡面取消注冊。
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        unregisterReceiver(bcrIntenal2);
    }    
    
}
發送的時候加了藍牙權限,
若在使用sendBroadcast()的方法是指定了接收權限,則只有接收方的包內--在androidManifest.XML中用<uses- permission>標簽聲明了擁有此權限的BroascastReceiver才會有可能接收到發送來的Broadcast。 
同樣,若在注冊BroadcastReceiver時指定了可接收的Broadcast的權限,則只有在接收方的包內的androidManifest.XML中用<uses-permission>標簽聲明了,擁有此權限的Context對象所發送的Broadcast才能被這個 BroadcastReceiver所接收。
main.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
    android:orIEntation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextVIEw  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button
    android:id="@+id/button01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="動態接收廣播true"/>
<Button
    android:id="@+id/button02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="動態接收廣播false"/>
</LinearLayout>
androidManifest.XML

代碼 
<?XML version="1.0" encoding="utf-8"?>
<manifest XMLns:android="http://schemas.android.com/apk/res/android"
      package="com.broad.test1"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BroadcastActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>    
</manifest> 
注意上面加的藍牙permission權限
運行結果:

總結:
以發送intent為例,發送廣播都用sendBroadcast(intent);
靜態注冊接收的時候,只需要
(1)得到action,如:
String action = intent.getAction();
(2)判斷action類型,做出相應的動作。
動態注冊接收的時候,需要:
(1) IntentFilter intentFilter= new IntentFilter();

(2)intentFilter.addAction(。。);可以添加多個
(3)注冊接收,registerReceiver(BroadcastReceiver對象,intentFilter);別忘了在其他需要的地方取消注冊接收!!!
(4)得到action,如:
 

String action = intent.getAction();
(5)判斷action類型,做出相應的動作。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved