Android開發:廣播機制:Broadcast——自定義廣播方法

廣播是一種信息的發送機制,就像電視那樣,用戶可以選擇自己喜歡的電視節目,電視臺(發送方)不會考慮用戶是如何對電視信息進行處理的,不管用戶是否在收看此頻道,點屍體愛都要發送電視信號。

在Android中存在着各種各樣的廣播信息,如手機剛啓動時的提示信息、電池不足的警告信息和來點信息等,都會通過廣播形式發送給用戶,而處理的形式由用戶自己決定。

在Android中開發者可以定義自己的廣播組件,但是所用的廣播組件都是一個類的形式出現,而且該類必須繼承自BroadcastReceive類,而且還需向Android系統註冊。

系統中定義了很多的廣播組件,分別代表不同的功能。然而有時候開發者需要自己定義廣播組件用到特定的APP中,下面例程介紹自定義廣播組件的方法。

佈局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
	android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="廣播" />
</LinearLayout>
<span style="color: rgb(255, 0, 0); font-size: 18px; "><strong>Java文件MainActivity.java</strong></span>
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	MyReceiver myr =  new MyReceiver();
    @Override
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) this.findViewById(R.id.button1);
        myButton.setOnClickListener(
        			new OnClickListener(){
						@Override
						public void onClick(View v) {
							Intent it = new Intent("LIZHAOJING");//自定義廣播
							it.putExtra("msg","lizhaojing");//放入自定義信息
							MainActivity.this.sendBroadcast(it);//發送廣播
							IntentFilter filter = new IntentFilter("LIZHAOJING");//接收廣播過濾器
							MainActivity.this.registerReceiver(myr,filter);//註冊廣播
						}
        			}
        		); 
    }
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(myr);//註銷廣播
		super.onDestroy();
	}
}

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver{//繼承自BroadcastReceiver
	@Override
	public void onReceive(Context context, Intent intent) {//重寫的onReceive方法
		if("LIZHAOJING".equals(intent.getAction())){
			String msg = intent.getStringExtra("msg");
			Toast.makeText(context, "廣播啓動"+msg, Toast.LENGTH_LONG).show();
		}
		
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章