本文實例為大家分享了Android學習之Broadcast的使用方法,供大家參考,具體內容如下
網站設計、網站建設的關注點不是能為您做些什么網站,而是怎么做網站,有沒有做好網站,給成都創(chuàng)新互聯公司一個展示的機會來證明自己,這并不會花費您太多時間,或許會給您帶來新的靈感和驚喜。面向用戶友好,注重用戶體驗,一切以用戶為中心。
實現開機啟動提示網絡的廣播
package com.example.luobo.broadcasttest; 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.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter = new IntentFilter();//創(chuàng)建一個過濾器實例 intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//添加接收CONNECTIVITY_CHANGE消息 networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeReceiver); } class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);//通過此方法獲取ConnectivityManager實例 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();//調用實例connectivityManager的getActiveNetworkInfo()方法獲取NetworkInfo實例 if (networkInfo != null && networkInfo.isAvailable()){ Toast.makeText(context,"Network is available",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(context,"Network is unavailable",Toast.LENGTH_SHORT).show(); } } } }
創(chuàng)建BootCompleteReceiver類
右擊com.example.luobo.broadcasttest,New->Other->Broadcast,輸入名字BootCompleteReceiver,勾選Enable,Exported,重寫onReceive()方法。由于使用的是快捷方式創(chuàng)建的類,所需權限會在AndroidManifest.xml中自動注冊。標簽為receiver,但是還不夠修改。
package com.example.luobo.broadcasttest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class BootCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"Boot Complete",Toast.LENGTH_SHORT).show(); } }
在AndroidMaifest.xml注冊權限
<?xml version="1.0" encoding="utf-8"?>//注冊接收網絡消息廣播 //注冊接收開機啟動廣播 //開機時系統(tǒng)會發(fā)一條此廣播
上述在AndroidMainfest.xml中注冊接收廣播消息屬于靜態(tài)注冊,在OnCreate()中注冊的接收廣播屬于動態(tài)注冊。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯。