自定義廣播分兩個步驟:1、發送廣播 2、接收廣播
一、先看如何接收廣播:
我使用的是Android Studio,File->New->Other->Broadcast Receiver,先創建一個廣播類,這個創建的類會自動幫我們繼承BroadcastReceiver類,接收廣播,需要繼承這個類
MyReceiver.java
package com.example.chenrui.app1; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "收到廣播", Toast.LENGTH_SHORT).show(); } }
上面的代碼,很簡單,就是在接收到廣播時,彈出一個toast提示框。
創建這個類時,同時會在AndroidManifest.xml注冊一個服務,注意紅色內容是在自動注冊的代碼上手工添加的內容:
<receiver android:name=".MyReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.example.chenrui.app1.broadcast1" /> </intent-filter> </receiver>
手工添加的內容,是指自定義廣播的廣播名稱,這個廣播名稱可以隨便定義,這個名稱在后面發送廣播的時候要用到。
二、發送廣播:
添加一個Activity,在界面上添加一個Button按鈕,然后編寫按鈕的onclick事件,注意紅色內容為主要代碼:
MainActivity.java
package com.example.chenrui.app1; import android.content.ComponentName; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.chenrui.app1.broadcast1"); intent.setComponent(new ComponentName("com.example.chenrui.app1","com.example.chenrui.app1.MyReceiver")); sendBroadcast(intent,null); } }); } }
紅色代碼第1行,指的是要發送一條廣播,並且指定了廣播的名稱,這個跟我們之前注冊的廣播名稱一一對應。
紅色代碼第2行,在Android 7.0及以下版本不是必須的,但是Android 8.0或者更高版本,發送廣播的條件更加嚴苛,必須添加這一行內容。創建的ComponentName實例化對象有兩個參數,第1個參數是指接收廣播類的包名,第2個參數是指接收廣播類的完整類名。
紅色代碼第3行,指的是發送廣播。
經過上面的步驟,完整的發送接收自定義廣播的例子就完成了。
實現效果(點擊按鈕時,會彈出一個toast提示信息):