作爲一個初學者,我試圖開發一個Android
應用程序,它從服務器數據庫獲取數據。如何檢查網絡可用性或檢查網絡並打開移動網絡?
這裏,如果Wi-Fi
目前還無法提供地方,我需要打開一個3G
- 或2G
- 數據,這是自動提供在Android設備上或者通過一個對話框打開移動網絡。
作爲一個初學者,我試圖開發一個Android
應用程序,它從服務器數據庫獲取數據。如何檢查網絡可用性或檢查網絡並打開移動網絡?
這裏,如果Wi-Fi
目前還無法提供地方,我需要打開一個3G
- 或2G
- 數據,這是自動提供在Android設備上或者通過一個對話框打開移動網絡。
如何檢查無線互聯網連接:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
添加權限清單中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
如何檢查是否針對移動互聯網連接(3G/LTE):
boolean is3g = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
// Checks if Mobile network is available ...
if(!is3g){
// IF MOBILE CONNECTION NOT AVAILBLE, OPEN SYSTEM SETTINGS FOR MOBILE NETWORKS
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
startActivity(intent);
}
希望這會有所幫助,請將其標記爲接受的答案,如果它爲您工作。
您可以檢查網絡是否可用,由該類
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible Internet providers
* **/
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
檢查互聯網
ConnectionDetector conn = new ConnectionDetector(youractivity.this);
if(conn.isConnectingToInternet()){
// call network operations
}else{
// Toast
}
希望這可以幫助你
使用本代碼來檢查網絡的可用性: -
public class CheckConnection {
private Context _context;
public CheckConnection(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
試試這個:
findViewById(R.id.button).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
// Check for n/w connection
if (!NetworkService
.isNetWorkAvailable(CurrentActivity.this)) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
CurrentActivity.this);
// set title
alertDialogBuilder.setTitle("Warning");
alertDialogBuilder
.setMessage("Check your network connection and try again.");
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setNegativeButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} else {
// Do your action if network exists
Intent i = new Intent(getApplicationContext(),NextActivity.class);
startActivity(i);
}
}
});
網絡服務。Java的:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class NetworkService {
private NetworkService() {}
public static boolean isNetWorkAvailable(final Context contextActivity) {
ConnectivityManager conMgr = (ConnectivityManager) contextActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
在清單中添加這些權限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
檢查網絡是否可用使用的代碼以下塊
private boolean isNetworkAvailable(Context mContext) {
// TODO Check network connection
ConnectivityManager connMgr = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
和未來做以下的檢查條件如果WIFI不可用: -
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} 你還需要這
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
// Checking for all possible internet providers
public boolean isConnectingToInternet(){
ConnectivityManager connectivity =
(ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
還指定這些權限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
findViewById ......真的嗎? – Ayub
@Ayub是的,findViewById你有什麼疑問? –
我認爲UI元素在這個問題上是無關緊要的,但是再一次,我可能是錯的 – Ayub