溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android學習筆記-廣播機制

發布時間:2020-07-18 13:07:15 來源:網絡 閱讀:1071 作者:umgsai 欄目:移動開發

Android廣播類似QT中的信號和槽~~~

Android學習筆記-廣播機制

發送方只負責發送廣播,不關心接收方是否接收到了信號,也不關心接收方如何處理信號。

界面文件activity_main.xml

   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/send1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView1"
        android:text="send 1" />
    
    <Button
        android:id="@+id/send2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/send1"
        android:text="send 2" />

MainActivity.java

public class MainActivity extends Activity {
	public static final String ACTION_1 = "send1~~~";
	public static final String ACTION_2 = "send2~~~~~~";
	private BroadcastReceiver receiver;
	private TextView textView = null;
	private Button button1 = null;
	private Button button2 = null;

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

		textView = (TextView) findViewById(R.id.textView1);
		textView.setText("");
		button1 = (Button) findViewById(R.id.send1);
		button2 = (Button) findViewById(R.id.send2);

		initView();
		receiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				String data = intent.getExtras().getString("data");
				if (action.equals(ACTION_1)) {
					textView.setText("");
					textView.setText("接收到:\n" + ACTION_1 + "\n1內容是:" + data);
				} else if (action.equals(ACTION_2)) {
					textView.setText("");
					textView.setText("接收到:\n" + ACTION_2 + "\n2內容是:" + data);
				}
			}

		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_1);
		filter.addAction(ACTION_2);
		registerReceiver(receiver, filter);
	}

	public void initView() {
		OnClickListener onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				int id = v.getId();
				switch (id) {
				case R.id.send1:
					Intent intent1 = new Intent(ACTION_1);
					intent1.putExtra("data", "action_01");
					sendBroadcast(intent1);
					break;
				case R.id.send2:
					Intent intent2 = new Intent(ACTION_2);
					intent2.putExtra("data", "action_02");
					sendBroadcast(intent2);
					break;
				default:
					break;
				}
			}
		};
		button1.setOnClickListener(onClickListener);
		button2.setOnClickListener(onClickListener);
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(receiver);//解除注冊
	}
}




下面的例子是Mars視頻中的例子

自定義接收器TestRecevier.java

public class TestRecevier extends BroadcastReceiver{

	public TestRecevier() {
		System.out.println("調用TestRecevier構造函數");
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		System.out.println("onReceive");	
	}

}


在AndroidManifest.xml文件中注冊接收器

        <!-- 定義一個廣播接收器,在其中配置只接收什么類型的廣播 -->
        <receiver android:name=".TestRecevier">
            <intent-filter >
            <!--接收到這個類型的Action時才觸發接收器-->
                <action android:name="android.intent.action.EDIT"/>
            </intent-filter>
        </receiver>

MainActivity.java

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());
	}

	class BroadcastListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			System.out.println("~~~~~~~~~~~");
			//TestRecevier testRecevier = new TestRecevier();
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_EDIT);
			//發送廣播
			MainActivity.this.sendBroadcast(intent);
		}
		
	}
}

點擊按鈕之后的輸入如下

11-24 13:53:33.288: I/System.out(24849): ~~~~~~~~~~~

11-24 13:53:33.288: I/System.out(24849): 調用TestRecevier構造函數

11-24 13:53:33.288: I/System.out(24849): onReceive




BroadcastRecevier用于監聽被廣播的時間(Intent)。為了達到這個目的,BroadcastRecevier必須進行注冊,兩種注冊方式:

  1. 在應用程序的代碼中進行注冊

  2. 在AndroidManifest.xml當中進行注冊

如果一個BroadcastRecevier用于更新UI,通常會使用第一種方式進行注冊,在Activity啟動的時候進行注冊,在Activity不可見以后取消注冊。


例:監聽接收短信,并且在控制臺輸出短信內容

MainActivity.java

public class MainActivity extends Activity {
	private Button registerButton = null;
	private Button unregisterButton = null;
	private SMSReceiver smsReceiver = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 registerButton = (Button)findViewById(R.id.register);
	        registerButton.setOnClickListener(new RegisterReceiverListener());
	        unregisterButton = (Button)findViewById(R.id.unregister);
	        unregisterButton.setOnClickListener(new UnRegisterReceiverListener());
	}

	   class RegisterReceiverListener implements OnClickListener{

			@Override
			public void onClick(View v) {
				System.out.println("開始監聽");
				//生成一個BroiadcastReceiver對象
				smsReceiver = new SMSReceiver();
				//生成一個IntentFilter對象
				IntentFilter filter = new IntentFilter();
				//為IntentFilter添加一個Action
				filter.addAction("android.provider.Telephony.SMS_RECEIVED");
				//將BroadcastReceiver對象注冊到系統當中
				MainActivity.this.registerReceiver(smsReceiver, filter);
			}
	    	
	    }
	    
	    class UnRegisterReceiverListener implements OnClickListener{

			@Override
			public void onClick(View v) {
				//解除BroadcastReceiver對象的注冊
				MainActivity.this.unregisterReceiver(smsReceiver);
			}
	    	
	    }
}

SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("receive message");
		
		//接受Intent對象當中的數據
		Bundle bundle = intent.getExtras();
		//在Bundle對象當中有一個屬性名為pdus,這個屬性的值是一個Object數組
		Object[] myOBJpdus = (Object[]) bundle.get("pdus"); 
		//創建一個SmsMessage類型的數組
        SmsMessage[] messages = new SmsMessage[myOBJpdus.length];  
        System.out.println(messages.length);
        for (int i = 0; i<myOBJpdus.length; i++) 
        {  
          //使用Object數組當中的對象創建SmsMessage對象
          messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);  
          //調用SmsMessage對象的getDisppalyMessageBody()方法,就可以得到消息的內容
          System.out.println(messages[i].getDisplayMessageBody());
        }
        try {
			Thread.sleep(30 * 1000);
			System.out.println("-------------------------------");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

在AndroidManifest.xml中配置讀取短信的權限

    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />




Android 系統廣播大全    

(參考http://blog.chinaunix.net/uid-25370280-id-1735613.html)

  1. String  ADD_SHORTCUT_ACTION  動作:在系統中添加一個快捷方式。

  2. String ALL_APPS_ACTION 動作:列舉所有可用的應用。輸入:無。

  3. String ALTERNATIVE_CATEGORY 類別:說明 activity 是用戶正在瀏覽的數據的一個可選操作。

  4. String ANSWER_ACTION 動作:處理撥入的電話。

  5. String BATTERY_CHANGED_ACTION 廣播:充電狀態,或者電池的電量發生變化。

  6. String BOOT_COMPLETED_ACTION 廣播:在系統啟動后,這個動作被廣播一次(只有一次)。

  7. String BROWSABLE_CATEGORY 類別:能夠被瀏覽器安全使用的 activities 必須支持這個類別。

  8. String BUG_REPORT_ACTION 動作:顯示 activity 報告錯誤。

  9. String CALL_ACTION 動作:撥打電話,被呼叫的聯系人在數據中指定。

  10. String CALL_FORWARDING_STATE_CHANGED_ACTION 廣播:語音電話的呼叫轉移狀態已經改。

  11. String CLEAR_CREDENTIALS_ACTION 動作:清除登陸憑證 (credential)。

  12. String CONFIGURATION_CHANGED_ACTION 廣播:設備的配置信息已經改變,參見 Resources.Configuration.

  13. Creator CREATOR 無 無

  14. String DATA_ACTIVITY_STATE_CHANGED_ACTION 廣播:電話的數據活動(data activity)狀態(即收發數據的狀態)已經改變。

  15. String DATA_CONNECTION_STATE_CHANGED_ACTION 廣播:電話的數據連接狀態已經改變。

  16. String DATE_CHANGED_ACTION 廣播:日期被改變。

  17. String DEFAULT_ACTION 動作:和 VIEW_ACTION 相同,是在數據上執行的標準動作。

  18. String DEFAULT_CATEGORY 類別:如果 activity 是對數據執行確省動作(點擊, center press)的一個選項,需要設置這個類別。

  19. String DELETE_ACTION 動作:從容器中刪除給定的數據。

  20. String DEVELOPMENT_PREFERENCE_CATEGORY 類別:說明 activity 是一個設置面板 (development preference panel).

  21. String DIAL_ACTION 動作:撥打數據中指定的電話號碼。

  22. String EDIT_ACTION 動作:為制定的數據顯示可編輯界面。

  23. String EMBED_CATEGORY 類別:能夠在上級(父)activity 中運行。

  24. String EMERGENCY_DIAL_ACTION 動作:撥打緊急電話號碼。

  25. int FORWARD_RESULT_LAUNCH 啟動標記:如果這個標記被設置,而且被一個已經存在的 activity 用來啟動新的 activity,已有 activity 的回復目標 (reply target) 會被轉移給新的 activity。

  26. String FOTA_CANCEL_ACTION 廣播:取消所有被掛起的 (pending) 更新下載。

  27. String FOTA_INSTALL_ACTION 廣播:更新已經被確認,馬上就要開始安裝。

  28. String FOTA_READY_ACTION 廣播:更新已經被下載,可以開始安裝。

  29. String FOTA_RESTART_ACTION 廣播:恢復已經停止的更新下載。

  30. String FOTA_UPDATE_ACTION 廣播:通過 OTA 下載并安裝操作系統更新。

  31. String FRAMEWORK_INSTRUMENTATION_TEST_CATEGORY 類別:To be used as code under test for framework instrumentation tests.

  32. String GADGET_CATEGORY 類別:這個 activity 可以被嵌入宿主 activity (activity that is hosting gadgets)。

  33. String GET_CONTENT_ACTION 動作:讓用戶選擇數據并返回。

  34. String HOME_CATEGORY 類別:主屏幕 (activity),設備啟動后顯示的第一個 activity。

  35. String INSERT_ACTION 動作:在容器中插入一個空項 (item)。

  36. String INTENT_EXTRA 附加數據:和 PICK_ACTIVITY_ACTION 一起使用時,說明用戶選擇的用來顯示的 activity;和 ADD_SHORTCUT_ACTION 一起使用的時候,描述要添加的快捷方式。

  37. String LABEL_EXTRA 附加數據:大寫字母開頭的字符標簽,和 ADD_SHORTCUT_ACTION 一起使用。

  38. String LAUNCHER_CATEGORY 類別:Activity 應該被顯示在頂級的 launcher 中。

  39. String LOGIN_ACTION 動作:獲取登錄憑證。

  40. String MAIN_ACTION 動作:作為主入口點啟動,不需要數據。

  41. String MEDIABUTTON_ACTION 廣播:用戶按下了“Media Button”。

  42. String MEDIA_BAD_REMOVAL_ACTION 廣播:擴展介質(擴展卡)已經從 SD 卡插槽拔出,但是掛載點 (mount point) 還沒解除 (unmount)。

  43. String MEDIA_EJECT_ACTION 廣播:用戶想要移除擴展介質(拔掉擴展卡)。

  44. String MEDIA_MOUNTED_ACTION 廣播:擴展介質被插入,而且已經被掛載。

  45. String MEDIA_REMOVED_ACTION 廣播:擴展介質被移除。

  46. String MEDIA_SCANNER_FINISHED_ACTION 廣播:已經掃描完介質的一個目錄。

  47. String MEDIA_SCANNER_STARTED_ACTION 廣播:開始掃描介質的一個目錄。

  48. String MEDIA_SHARED_ACTION 廣播:擴展介質的掛載被解除 (unmount),因為它已經作為 USB 大容量存儲被共享。

  49. String MEDIA_UNMOUNTED_ACTION 廣播:擴展介質存在,但是還沒有被掛載 (mount)。

  50. String MESSAGE_WAITING_STATE_CHANGED_ACTION 廣播:電話的消息等待(語音郵件)狀態已經改變。

  51. int MULTIPLE_TASK_LAUNCH 啟動標記:和 NEW_TASK_LAUNCH 聯合使用,禁止將已有的任務改變為前景任務 (foreground)。

  52. String NETWORK_TICKLE_RECEIVED_ACTION 廣播:設備收到了新的網絡 "tickle" 通知。

  53. int NEW_TASK_LAUNCH 啟動標記:設置以后,activity 將成為歷史堆棧中的第一個新任務(棧頂)。

  54. int NO_HISTORY_LAUNCH 啟動標記:設置以后,新的 activity 不會被保存在歷史堆棧中。

  55. String PACKAGE_ADDED_ACTION 廣播:設備上新安裝了一個應用程序包。

  56. String PACKAGE_REMOVED_ACTION 廣播:設備上刪除了一個應用程序包。

  57. String PHONE_STATE_CHANGED_ACTION 廣播:電話狀態已經改變。

  58. String PICK_ACTION 動作:從數據中選擇一個項目 (item),將被選中的項目返回。

  59. String PICK_ACTIVITY_ACTION 動作:選擇一個 activity,返回被選擇的 activity 的類(名)。

  60. String PREFERENCE_CATEGORY 類別:activity是一個設置面板 (preference panel)。

  61. String PROVIDER_CHANGED_ACTION 廣播:更新將要(真正)被安裝。

  62. String PROVISIONING_CHECK_ACTION 廣播:要求 polling of provisioning service 下載最新的設置。

  63. String RUN_ACTION 動作:運行數據(指定的應用),無論它(應用)是什么。

  64. String SAMPLE_CODE_CATEGORY 類別:To be used as an sample code example (not part of the normal user experience).

  65. String SCREEN_OFF_ACTION 廣播:屏幕被關閉。

  66. String SCREEN_ON_ACTION 廣播:屏幕已經被打開。

  67. String SELECTED_ALTERNATIVE_CATEGORY 類別:對于被用戶選中的數據,activity 是它的一個可選操作。

  68. String SENDTO_ACTION 動作:向 data 指定的接收者發送一個消息。

  69. String SERVICE_STATE_CHANGED_ACTION 廣播:電話服務的狀態已經改變。

  70. String SETTINGS_ACTION 動作:顯示系統設置。輸入:無。

  71. String SIGNAL_STRENGTH_CHANGED_ACTION 廣播:電話的信號強度已經改變。

  72. int SINGLE_TOP_LAUNCH 啟動標記:設置以后,如果 activity 已經啟動,而且位于歷史堆棧的頂端,將不再啟動(不重新啟動) activity。

  73. String STATISTICS_REPORT_ACTION 廣播:要求 receivers 報告自己的統計信息。

  74. String STATISTICS_STATE_CHANGED_ACTION 廣播:統計信息服務的狀態已經改變。

  75. String SYNC_ACTION 動作:執行數據同步。

  76. String TAB_CATEGORY 類別:這個 activity 應該在 TabActivity 中作為一個 tab 使用。

  77. String TEMPLATE_EXTRA 附加數據:新記錄的初始化模板。

  78. String TEST_CATEGORY 類別:作為測試目的使用,不是正常的用戶體驗的一部分。

  79. String TIMEZONE_CHANGED_ACTION 廣播:時區已經改變。

  80. String TIME_CHANGED_ACTION 廣播:時間已經改變(重新設置)。

  81. String TIME_TICK_ACTION 廣播:當前時間已經變化(正常的時間流逝)。

  82. String UMS_CONNECTED_ACTION 廣播:設備進入 USB 大容量存儲模式。

  83. String UMS_DISCONNECTED_ACTION 廣播:設備從 USB 大容量存儲模式退出。

  84. String UNIT_TEST_CATEGORY 類別:應該被用作單元測試(通過 test harness 運行)。

  85. String VIEW_ACTION 動作:向用戶顯示數據。

  86. String WALLPAPER_CATEGORY 類別:這個 activity 能過為設備設置墻紙。

  87. String WALLPAPER_CHANGED_ACTION 廣播:系統的墻紙已經改變。

  88. String WALLPAPER_SETTINGS_ACTION 動作:顯示選擇墻紙的設置界面。輸入:無。

  89. String WEB_SEARCH_ACTION 動作:執行 web 搜索。

  90. String XMPP_CONNECTED_ACTION 廣播:XMPP 連接已經被建立。

  91. String XMPP_DISCONNECTED_ACTION 廣播:XMPP 連接已經被斷開。


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女