歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 交互功能組件BroadcastReceiver 的簡單使用

Android 交互功能組件BroadcastReceiver 的簡單使用

日期:2017/3/1 9:44:59   编辑:Linux編程

大多數簡單的應用程序都是相互獨立,相互隔離,而復雜的應用程序需要和硬件,原始組件產生交互。鑒於此,Android也提供了一些供應用程序交互的功能組件。

主要包括:BroadcastReceiver , Intent, Adapters,ContentProviders。

本篇簡單講述BroadcastReceiver的使用,記錄自己的學習經歷。

BroadcastReceiver使用主要包含幾個部分,一是繼承BroadcastReceiver類,實現onReceive方法;二是廣播消息發送的源頭(sendBroadcast);三是數據信息的傳遞

首先,實現一個IntentTestActivity繼承Activity,添加一個按鈕,單擊後發送一個廣播消息

package com.android.test;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class IntentTestActivity extends Activity {
/** Called when the activity is first created. */
private static Button button = null;
private static int nCount = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

button = (Button)findViewById(R.id.send_button);
button.setBackgroundColor(Color.GRAY);
button.setHighlightColor(Color.RED);

button.setOnClickListener(new OnClickListener() { // 添加按鍵監聽器

public void onClick(View v) {
// TODO Auto-generated method stub
Intent itent = new Intent();
itent.setAction("com.android.IntetTest"); // 指定Intent的action 行為
itent.putExtra("data", nCount++);// 此處為了便於測試發送一個整數
IntentTestActivity.this.sendBroadcast(itent); // 通過Intent來啟動廣播並發送廣播消息

Toast.makeText(IntentTestActivity.this,"發送廣播消息"+"["+nCount+"]", Toast.LENGTH_SHORT).show();
}
});

setContentView(R.layout.main);
}
}

說明:發送廣播消息以Intent為橋梁,將此次Intent意圖對應的action行為發送給廣播接收者,對於數據的傳遞putExtra( )可以傳遞多種類型的數據以及bundle

接著,實現廣播接收器MyReceiver,繼承BroadcastReceiver,實現onReceive接口,來完成廣播的接收,並作相應的操作

package com.android.test;

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

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().toString().equals("com.android.IntetTest")){ // 注意此處的Intent的action要對應廣播發送者發送時的action
int value = intent.getExtras().getInt("data"); // 接收廣播中傳送的數據
// 收到信息之後顯示一下,可做其他對應操作
Toast.makeText(context, "收到廣播消息"+"["+value+"]", Toast.LENGTH_SHORT).show();
}
}

}

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-05/101048p2.htm

Copyright © Linux教程網 All Rights Reserved