Android Programming

Hands On No. 7 : Wifi,Bluetooth,GPS Access using Andorid

Resources

Source Code of MainAcivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1 = (Button) findViewById(R.id.showstatus);
final TextView tv1 = (TextView) findViewById(R.id.status);

b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = new StringBuffer();

s1 = "";
s2 = "";
s3 = "";
final WifiManager wmgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
internet = wmgr.isWifiEnabled();

if (internet == true) {
s1 = "Wifi is On";
} else {
s1 = "Wifi is Off";
}

s.append(s1);
final BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
if (bAdapter == null) {
s2 = "Bluetooth is supported";
} else if (!bAdapter.isEnabled()) {
s2 = "Bluetooth is Off";
} else if (bAdapter.isEnabled()) {
s2 = "Bluetooth is On";
}

s.append("\n" + s2);

s3 = "";
LocationManager lm = (LocationManager) getSystemService(Context. LOCATION_SERVICE ) ;
boolean gps_enabled = false;
gps_enabled = lm.isProviderEnabled(LocationManager. GPS_PROVIDER );
if (gps_enabled == true) {
s3 = "GPS is On";
} else {
s3 = "GPS is Off";
}
s.append("\n" + s3);
tv1.setText(s.toString());
}
});
}

Source Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >


<Button
android:id="@+id/showstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Show Status" />

<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:text="Will appear here"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

</RelativeLayout>

Permission should be added in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>