android中實現自定義廣播
阿新 • • 發佈:2019-01-14
自定義廣播分兩個步驟: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提示資訊):