編輯:關於Android編程
最近在做APP,需要監聽Android手機網絡的變化情況,同時對不同的情況做出不同的響應策略,這裡有兩種方法。
這裡我使用的是ConnectivityManager和NetworkInfo兩個類來實現的。詳細代碼如下:
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * Created on 2016/10/31. * 網絡狀態判斷 */ public class NetWorkUtils { public Context context = null; public NetWorkUtils(Context context) { this.context = context; } public static MyApplication getApplication() { return MyApplication.getInstance(); } /** * 判斷是否聯網 */ public static boolean isConnectNET(final Context context) { final ConnectivityManager conManage = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = conManage.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { return true; } else { Toast.makeText(context, "斷網了,請檢查網絡~", Toast.LENGTH_SHORT).show(); return false; } } }
單單使用BroadcastReceiver來實現監聽。
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.jiketuandui.antinetfraud.Activity.NetWorkErrorActivity; import com.jiketuandui.antinetfraud.Util.NetWorkUtils; /** * Created on 2016/10/31. * 使用廣播來監聽“網絡連接”的情況 * 當網絡連接不存在的時候(斷網),NetWorkUtils.isConnectNET(context) * 返回false,這個時候我們就跳轉到一個錯誤提示的Activity中,提示用戶聯網 */ public class NETChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (!NetWorkUtils.isConnectNET(context)) { intent.setClass(context, NetWorkErrorActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } }
1.為了獲取上網的權限,和檢測網絡狀態,我們需要添加權限
2.在Manifest中配置BroadReceiver監測斷網,action裡面是網絡連接變化時候來觸發這個Receiver,如下所示:
這個方法的缺點就是需要在Activity中注冊廣播,在APP中就不大適用,因為一個Application中不可能只有一個Activity,而且我們也不可能每一個都去注冊一邊,太麻煩了,所以有了以下的方法。
主要就是找一個可以獨立於眾多Activity的載體去承載BroadcastReceiver
,實現對整一個Application的網絡監控。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxoMyBpZD0="原理">原理
原理其實就是在程序的後台創建一個看不見的服務(Service),在Service中注冊一個廣播(BroadcastReceiver),當網路發生變化的時候就可以產生一個ConnectivityManager.CONNECTIVITY_ACTION的事件,只要我們監聽這個事件就可以實現實時監聽網絡變化了。
當然,也不要忘記在中配置一下
package com.notzuonotdied.monitor_network_changes; import android.app.Service; 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.IBinder; import android.util.Log; /** * Created by Notzuonotdied on 2016/10/31. * 檢測網絡的Service服務 */ public class NetworkStateService extends Service { private ConnectivityManager connectivityManager; private NetworkInfo info; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); info = connectivityManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { String name = info.getTypeName(); intent.setClass(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { intent.setClass(context, NetWorkErrorActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } }; @Override public IBinder onBind(Intent intent) { return null; } /** * 注冊BroadcastReceiver * */ @Override public void onCreate() { super.onCreate(); IntentFilter mFilter = new IntentFilter(); mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, mFilter); } /** * 當被銷毀的時候,我們要把BroadcastReceiver注銷 * */ @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } }
package com.notzuonotdied.monitor_network_changes; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * Created by Notzuonotdied on 2016/10/31. * 網絡狀態判斷 */ public class NetWorkUtils { public Context context = null; public NetWorkUtils(Context context) { this.context = context; } /** * 判斷是否聯網 */ public static boolean isConnectNET(final Context context) { final ConnectivityManager conManage = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = conManage.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { return true; } else { Toast.makeText(context, "斷網了,請檢查網絡~", Toast.LENGTH_SHORT).show(); return false; } } }
package com.notzuonotdied.monitor_network_changes; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Notzuonotdied on 2016/11/2. * 從客戶端獲取數據 */ public class getConnect { @Nullable public static String doGet(String mURL) throws IOException { HttpURLConnection httpURLConnection; BufferedReader reader = null; StringBuffer stringBuffer = null; try { httpURLConnection = (HttpURLConnection) new URL(mURL).openConnection(); httpURLConnection.setRequestProperty("Accept-Charset", "utf-8"); // 數據流 reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); stringBuffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } if (stringBuffer == null) { return null; } return stringBuffer.toString(); } }
package com.notzuonotdied.monitor_network_changes; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; /** * 2016年11月2日 09:15:39 * */ public class MainActivity extends AppCompatActivity { private android.widget.Button btn; private android.widget.TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initService(); initView(); initListener(); } /** * 初始化Service進行監聽網絡 */ private void initService() { Intent i = new Intent(this, NetworkStateService.class); startService(i); } /** * 初始化響應事件 */ private void initListener() { btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (NetWorkUtils.isConnectNET(MainActivity.this)) { new getData().execute(); } } }); } /** * 初始化UI */ private void initView() { this.tv = (TextView) findViewById(R.id.tv); this.btn = (Button) findViewById(R.id.btn); } /** * 為了不讓主線程堵塞,影響用戶體驗,使用異步任務來訪問網絡 */ class getData extends AsyncTask{ @Override// 在子線程中doSomething protected String doInBackground(Void... voids) { String str = null; try { str = getConnect.doGet("http://www.csdn.com"); } catch (IOException e) { e.printStackTrace(); } return str; } @Override// 獲取數據完成,返回到主線程來更新主線程 protected void onPostExecute(String s) { tv.setText(s); super.onPostExecute(s); } } }
package com.notzuonotdied.monitor_network_changes; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class NetWorkErrorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_net_work_error); } }
兩行代碼,用最簡單的方式來實現Android視圖擴散切換效果。一、概述這兩天時間動手撸了個視圖擴散切換效果的控制器,API兼容至Android4.0,更方便我們在視圖切
Socket Android手機客戶端與PC服務端局域網內聯測試,筆者采用的是 PC服務器,Android平板客戶端 ,PC模擬器客戶端, 前段時間為了加深對Socket
Android Studio原生支持使用Gradle來構建項目,使用動態語言Groovy定義項目構建的過程,避免了build.xml文件繁瑣的定義。然而使用的時候,卻有著
Android注解越來越引領潮流,比如 Dagger2, ButterKnife, EventBus3 等,他們都是注解類型,而且他們都有個共同點就是編譯時生成代碼,而不