Android連載22-自定義廣播之標準廣播發送

1、發送自定義廣播

1.廣播主要分爲兩種:

  • 標準廣播和有序廣播

2.發送標準廣播

  • 先定義一個廣播接收器來接收廣播
package com.example.broadcasttest2;

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

public class MyBroadcastReceiver extends BroadcastReceiver {
 
 @Override
 public void onReceive(Context context,Intent intent) {
  Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
 }
 
}
 
  • 上面的代碼意義在於接收到自定義廣播的時候,就會彈出"received in MyBroadcastReceiver"這句話,而後在AndroidManifest.xml中註冊這個類
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

      ..........................................
        
        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
    </application>
  • 上面的XML就是當定義的接收器接收到值com.example.broadcasttest.MY_BROADCAST的時候纔會觸發那個定義好的廣播器
  • 接下來咱們能夠猜到就是觸發這條廣播唄,咱們用個按鈕來觸發這個廣播吧
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 ..........................................
        android:id="@+id/button"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "Send Broadcast"
        />
</LinearLayout>

 

package com.example.broadcasttest2;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 private IntentFilter intentFilter;
 
 private NetworkChangeReceiver networkChangeReceiver;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
    
  Button button = (Button) findViewById(R.id.button);
  button.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
    sendBroadcast(intent);
   }
  });
 } 
}

 

運行打包安裝:
22.1android

  • 咱們點擊一下按鈕
    22.2
  • 首先構建出了一個Intent對象,並把要發送的廣播的值傳入,而後調用了Context的sendBroadcast()方法將廣播發送出去,這樣全部監聽com.example.broadcasttest.MY_BROADDCAST這條廣播的廣播接收器就會收到消息。此時發出去的廣播就是一條標準廣播。

2、源碼:

相關文章
相關標籤/搜索