網路功能在手機上是很重要的,許多android app都很依賴是否有網路來進行後續的行為,下述記錄如何判斷目前的手機有開啟網路功能。
首先,要先在 AndroidManifest.xml中加上網錄讀取的權限,如下:
<?xml version="1.0" encoding="utf-8"?> |
確定後就能在程式中加上判斷網路的功能:
import androidx.appcompat.app.AlertDialog; | |
import androidx.appcompat.app.AppCompatActivity; | |
import android.content.DialogInterface; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.Bundle; | |
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
//判斷網路 | |
ConnectivityManager conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);//先取得此service | |
NetworkInfo networInfo = conManager.getActiveNetworkInfo(); //在取得相關資訊 | |
if (networInfo == null || !networInfo.isAvailable()) { | |
new AlertDialog.Builder(MainActivity.this) | |
.setTitle("提醒") | |
.setMessage("沒有網路可用,請檢查網路狀態") | |
.setCancelable(false) | |
.setPositiveButton("我知道了", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
} | |
}) | |
.show(); | |
}else{ | |
new AlertDialog.Builder(MainActivity.this) | |
.setTitle("提醒") | |
.setMessage("有網路可用") | |
.setCancelable(false) | |
.setPositiveButton("我知道了", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
} | |
}) | |
.show(); | |
} | |
} | |
} |
上述的15, 16行就是先取得service,再從service中取得網路狀態,然後line 18 就是判定其網路狀態。
部屬到手機上的圖片如下:
Reference:
https://sites.google.com/site/chengshixuexipingtai/android/pan-duan-wang-lu