Banyak aplikasi Android yang membutuhkan koneksi internet. Nah, jika kita membuat aplikasi yang membutuhkan koneksi internet tetapi tidak ada, maka program tersebut akan error. Ada baiknya sebelum program tersebut menjalankan proses yang membutuhkan koneksi internet, kita deteksi tersebih dahulu secara otomatis apakah Device Android tersambung ke Internet atau belum. Jika belum bisa kita buka Setting secara otomatis sehingga user tidak perlu susah-susah membuka setting Wireless Connection.
Silakan buat Project Android. Pada Program utama di MainActivity kita tambahkan beberapa baris program seperti di bawah ini :
MainActivity.java
package com.amijaya.androiddetectinternet;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;
//http://cariprogram.blogspot.com
//nuramijaya@gmail.com
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isConnectingToNetwork()) {
if (hasActiveInternetConnection())
{
Toast.makeText(getApplicationContext(), "Terkoneksi dengan Jaringan Internet", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Terkoneksi dengan Jaringan tetapi Koneksi Internet Disconnect,\n Buka Setting dan Ubah Jaringan?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
else
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Network Connection, Buka Setting dan Aktifkan Jaringan?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
public boolean isConnectingToNetwork(){
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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;
}
public boolean hasActiveInternetConnection() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error checking internet connection", Toast.LENGTH_LONG).show();
}
return false;
}
}
Selanjutnya pada layout tampilan tidak ada lagi perubahan, bisa digunakan saja tampilan default :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Pada setting konfigurasi di Android Manifest, kita harus tambahkan Permission untuk melakukan koneksi ke Internet. Tambahkan baris seperti di bawah ini :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.amijaya.androiddetectinternet"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Hasilnya :
Project selengkapnya silakan didownload disini :
https://docs.google.com/open?id=0B4i1FYc_4RXzZzEwREVORXJGOUU
Semoga bermanfaat, Selamat Coding.