- 以下CheckInternetConnActivity.java有檢查網路的兩種寫法
1-1. 檢查行動網路或WIFI使否正常連線,不包含身分驗證網路
1-2. 檢查行動網路或WIFI與包含需要身分驗證網路是否連線正常
1-1. CheckInternetConnActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class CheckInternetConnActivity extends Activity {
// Internet status flag
private Boolean isConnectionExist = false;
// Connection detector class
private InternetConnectionDetector internetCD;
private static int WIFI_CONNECTED_STATUS = 0,
MOBILE_INTERNET_CONNECTED_STATUS = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_internet_conn);
Button btnStatus = (Button) findViewById(R.id.btn_check);
// creating connection detector class instance
internetCD = new InternetConnectionDetector(getApplicationContext());
// Button click listener to check internet status
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get Internet status
isConnectionExist = internetCD.checkMobileInternetConn();
// check for Internet status
if (isConnectionExist) {
// Internet Connection exists
showAlertDialog(CheckInternetConnActivity.this,
"Internet Connection",
"Your device has Internet access", true);
} else {
// Internet connection doesn't exist
showAlertDialog(CheckInternetConnActivity.this,
"No Internet Connection",
"Your device doesn't have Internet access", false);
}
}
});
}
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? android.R.drawable.star_big_on
: android.R.drawable.ic_delete);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private class InternetConnectionDetector {
private Context context;
public InternetConnectionDetector(Context context) {
this.context = context;
}
public boolean checkMobileInternetConn() {
// Create object for ConnectivityManager class which returns network
// related info
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// If connectivity object is not null
if (connectivity != null) {
// Get network info - WIFI internet access
NetworkInfo[] internetInfo = {
connectivity
.getNetworkInfo(ConnectivityManager.TYPE_WIFI),
connectivity
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) };
if (internetInfo[WIFI_CONNECTED_STATUS] != null
|| internetInfo[MOBILE_INTERNET_CONNECTED_STATUS] != null) {
// Look for whether device is currently connected to WIFI
// network
if (internetInfo[WIFI_CONNECTED_STATUS].isConnected()
|| internetInfo[MOBILE_INTERNET_CONNECTED_STATUS]
.isConnected()) {
return true;
}
}
}
return false;
}
}
}
1-2. CheckInternetConnActivity.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class CheckInternetConnActivity extends Activity {
private ProgressDialog progresslog;
private String url = "http://mylinandroidcode.blogspot.tw/";
private String authen_network = "check";
private int authen_html_len = 801;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_internet_conn);
Button btnStatus = (Button) findViewById(R.id.btn_check);
// creating connection detector class instance
// Button click listener to check internet status
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new CheckInternetConnActivity.CheckInternetConnTask(
CheckInternetConnActivity.this).execute(url);
}
});
}
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? android.R.drawable.star_big_on
: android.R.drawable.ic_delete);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private class CheckInternetConnTask extends
AsyncTask<String, Integer, String> {
private String checkStr = "";
private Context context;
public CheckInternetConnTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(CheckInternetConnActivity.this, 1);
progresslog.setCanceledOnTouchOutside(false);
progresslog.setMessage("Check internet connection...");
progresslog.show();
}
@Override
protected String doInBackground(String... connStr) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(connStr[0]);
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
do {
checkStr += reader.readLine();
if (checkStr.length() > authen_html_len) {
checkStr = authen_network;
return checkStr;
}
} while (reader.readLine() != null);
} catch (Exception io) {
}
return checkStr;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
if (result.equals(authen_network)) {
showAlertDialog(context, "Check network",
"Internet connection of normal", true);
} else {
showAlertDialog(context, "Check network",
"Please check network whether can connection", false);
}
}
}
}
2. activity_check_internet_conn.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Check Internet Status" />
</RelativeLayout>
3. AndroidManifest.xml(重點程式碼)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
沒有留言:
張貼留言