Android UNIT 3
Android UNIT 3
ARRAY ADAPTER
An adapter basically connects the User Interfaces and the Data Source. It
converts data from the data sources into view items that can be displayed into
the UI Component. Data Source can be Arrays, HashMap, Database, etc. and
UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the
most commonly used adapter in android. When you have a list of single type
items which are stored in an array you can use ArrayAdapter. The array
adapter uses Object.toString() for each data object to create a view, and
then place the result in a TextView. This type of android adapter is used for
ListView, GridView or Spinner.
ArrayAdapter is a class and can have various types of Constructors, those
constructors are mentioned below:
Description
Parameter
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/itemTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
ListView simpleListView;
// array objects
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleListView.setAdapter(arrayAdapter);
OUTPUT
There are certain methods of Adapter class that are mentioned below:
ListView
A ListView is a type of AdapterView that displays a vertical list of scroll-able
views and each view is placed one below the other. Using adapter, items are
inserted into the list from an array or database. For displaying the items in the
list method setAdaptor() is used. Android ListView is a ViewGroup that is used
to display the list of items in multiple rows and contains an adapter that
automatically inserts the items into the list.
The main purpose of the adapter is to fetch data from an array or database and
insert each item that placed into the list for the desired result.
Attribute Description
LIST ACTIVITY
ListActivity is a subclass of Activity that includes a ListView object.
Through ListActivity class you can create an activity in your Android application that can
be connected to different data sources (query cursor or arrays) and can be displayed as a
set of list items on the screen. Actually, the use of the ListActivity class provides us a
more simplified way of handling the list of items because it contains a ListView by default.
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Mainactivity.java
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MAIN ACTIVITY.JAVA
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public int getCount() {
return names.length;
}
@Override
public Object getItem(int position) {
return names[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView =
LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, parent, false);
}
TextView textView = convertView.findViewById(R.id.textView);
textView.setText(names[position]);
return convertView;
}
}
}
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>
</LinearLayout>
MAIN ACTIVITY.JAVA
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public int getCount() {
return colors.length;
}
@Override
public Object getItem(int position) {
return colors[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView =
LayoutInflater.from(MainActivity.this).inflate(R.layout.grid_item, parent, false);
}
return convertView;
}
}
}
CUSTOM TABS
Creating custom tabs in Android can be a useful way to implement tabbed navigation in your
app with a unique design or behavior. To create custom tabs, you'll typically use a combination
of views, layouts, and view pager for swappable tab content. In Android programming, the term
"custom tabs" refers to the capability of designing and styling tabbed user interfaces in Android
applications. An app's content and navigation can be organized using tabs, a standard UI
component. Although custom tabs provide developers complete control over the look and
behavior of tabs, Android comes with a default Tab Layout widget that makes the
implementation of tabs easier.
<Button
android:id="@+id/idBtnCustomChromeTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Custom Chrome Tabs" />
</RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the
code for the MainActivity.java file. Comments are added inside the code to
understand the code in more detail.
Main.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat;
Button Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customIntent.setToolbarColor(ContextCompat.getColor(MainActivity.this,
R.color.purple_200));
STRING ARRAY
A string array is a data structure used in Android programming that contains an
organized group of strings. A list of string values or other resources that you want
to use in your Android application are frequently stored there. String arrays are
widely used for a variety of things, including establishing resource names,
populating spinner widgets, showing menu items, and more.
Define a String Array in res/values/strings.xml:
Open the res/values/strings.xml file and define your string array inside the
<resources> section. For example:
<resources>
<string-array name="my_string_array">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<!-- Add more items as needed -->
</string-array>
</resources>
Main.java
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
Creating list
Same as list view
THREADS
In Android programming, threads are used to perform tasks, allowing your app to
remain responsive and avoid freezing or lagging. Threads are essential for handling
time-consuming operations, such as network requests or heavy computations, without
blocking the main thread. Android provides several mechanisms for working with
threads:
1. UI Thread (Main Thread): The UI thread, also known as the main thread, is the primary
thread in an Android application responsible for handling the user interface and its
interactions. All user interface components, such as UI widgets and views, are created,
updated, and interacted with on this thread. It's crucial to keep the UI thread responsive,
as any long-running or blocking operations on this thread can lead to the app
becoming unresponsive and potentially causing an Application Not Responding (ANR)
error.
BACKGROUND THREAD: In Android programming, a background thread is any thread that is
not the main UI thread (also known as the main thread). Background threads are used to
perform tasks that are not directly related to the user interface, such as network requests, file
I/O, data processing, or any operation that might take a significant amount of time to complete.
Using background threads is essential to prevent blocking the UI thread, which could result in an
unresponsive or frozen user interface.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
protected void onPostExecute(String result) {
// Update UI with the results
resultTextView.setText(result);
}
}
}
MULTI THREADING
Working on multiple tasks at the same time is Multitasking. In the same way,
multiple threads running at the same time in a machine is called Multi-
Threading. It allows an app to perform multiple tasks simultaneously, improving performance
and responsiveness.
Run on UI Thread
"Run on UI thread" refers to the action of executing a piece of code on the UI thread, even if
that code is currently running on a background thread. This is necessary when you need to
update the user interface because UI updates should always be performed on the UI thread to
ensure a smooth and responsive user experience. There are methods and mechanisms provided
in Android, such as runOnUiThread() and Handler, that allow you to perform tasks for
execution on the UI thread from a background thread.
Worker thread
In Android programming, a worker thread is a thread specifically designated to perform
background tasks, such as lengthy computations, network operations, or other I/O-bound
operations. The primary purpose of worker threads is to offload work from the main UI thread
(also known as the main thread) to ensure that the user interface remains responsive and
doesn't become blocked during time-consuming operations.
Handler:
A Handler is an Android class that provides a mechanism for scheduling and executing
code on a specific thread. It is often used to perform tasks on the main/UI thread or
other background threads.
A Handler is associated with a particular Looper, which represents a message loop for a
thread. The main/UI thread already has a Looper, so you can create a Handler for it
directly. For background threads, you can create a Handler associated with a
HandlerThread or other custom threads.
The primary function of a Handler is to post Runnable tasks for execution on a thread's
message queue. These tasks are typically implemented as anonymous inner classes that
implement the Runnable interface.
Handler mainHandler = new
Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
// Code to update the UI here
}
});
RUNNABLE
In Android, a Runnable is a fundamental interface used to represent a block of code that can be
executed on a separate thread. Runnable instances are commonly used to perform background
tasks or execute code asynchronously without blocking the main/UI thread, thus ensuring the
responsiveness of the user interface. You create a Runnable by implementing its run()
method, which contains the code you want to execute. This code typically represents the
background task you want to perform.
The three generic types used in an android AsyncTask class are given below :
Params : The type of the parameters sent to the task upon execution
Progress : The type of the progress units published during the background computation
Result : The type of the result of the background computation
SENSORS
Types of Sensors
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three
axes.
2) Position Sensors
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity
etc.
4 Gyroscope Sensor:
Measures angular velocity around the device's three axes.
Used for precise motion tracking and orientation detection in 3D space.
5 Magnetometer (Compass) Sensor:
Measures the strength and direction of the magnetic field around the device.
Used for determining the device's orientation relative to the Earth's magnetic
field and for implementing compass apps.
6 Proximity Sensor:
Detects when an object is close to the device (usually used for detecting when
the user's face is near during phone calls to turn off the screen).
Often used to implement "pocket mode" to prevent accidental touch input.
7 Light Sensor:
8 Measures ambient light levels.
9 Used to automatically adjust screen brightness based on lighting conditions and
for detecting changes in lighting.
USING ORIENTATION
To obtain the orientation of a device in Android using sensors, you typically combine data from
the accelerometer and magnetometer (compass) sensors. The orientation is represented as
azimuth, pitch, and roll angles, which describe the device's orientation along its yaw, pitch, and
roll axes, respectively
ACCELEROMETER
The accelerometer sensor in Android is a hardware component that measures the acceleration
of the device along its three primary axes: X, Y, and Z. It provides data related to the device's
motion and orientation changes. Accelerometers are commonly used in various applications,
including games, fitness tracking, screen rotation, and gesture recognition.
TELEPHONY
The android.telephony.TelephonyManager class provides information about the telephony
services such as subscriber id, sim serial number, phone network type etc. Moreover, you can
determine the phone state etc. IN Android programming, you can implement telephony services
to interact with the phone's telephony features such as making calls, sending SMS messages,
and monitoring phone state. To work with telephony services in Android, you typically use the
TelephonyManager class and request the necessary permissions in your AndroidManifest.xml
file.
activity_main.xml
Drag one textview from the pallete, now the xml file will look like this.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="38dp"
18. android:layout_marginTop="30dp"
19. android:text="Phone Details:" />
20.
21. </RelativeLayout>
Activity class
Now, write the code to display the information about the telephony services.
File: MainActivity.java
1. package com.javatpoint.telephonymanager;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Context;
6. import android.telephony.TelephonyManager;
7. import android.view.Menu;
8. import android.widget.TextView;
9.
10. public class MainActivity extends Activity {
11. TextView textView1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. textView1=(TextView)findViewById(R.id.textView1);
18.
19. //Get the instance of TelephonyManager
20. TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVI
CE);
21.
22. //Calling the methods of TelephonyManager the returns the information
23. String IMEINumber=tm.getDeviceId();
24. String subscriberID=tm.getDeviceId();
25. String SIMSerialNumber=tm.getSimSerialNumber();
26. String networkCountryISO=tm.getNetworkCountryIso();
27. String SIMCountryISO=tm.getSimCountryIso();
28. String softwareVersion=tm.getDeviceSoftwareVersion();
29. String voiceMailNumber=tm.getVoiceMailNumber();
30.
31. //Get the phone type
32. String strphoneType="";
33.
34. int phoneType=tm.getPhoneType();
35.
36. switch (phoneType)
37. {
38. case (TelephonyManager.PHONE_TYPE_CDMA):
39. strphoneType="CDMA";
40. break;
41. case (TelephonyManager.PHONE_TYPE_GSM):
42. strphoneType="GSM";
43. break;
44. case (TelephonyManager.PHONE_TYPE_NONE):
45. strphoneType="NONE";
46. break;
47. }
48.
49. //getting information if phone is in roaming
50. boolean isRoaming=tm.isNetworkRoaming();
51.
52. String info="Phone Details:\n";
53. info+="\n IMEI Number:"+IMEINumber;
54. info+="\n SubscriberID:"+subscriberID;
55. info+="\n Sim Serial Number:"+SIMSerialNumber;
56. info+="\n Network Country ISO:"+networkCountryISO;
57. info+="\n SIM Country ISO:"+SIMCountryISO;
58. info+="\n Software Version:"+softwareVersion;
59. info+="\n Voice Mail Number:"+voiceMailNumber;
60. info+="\n Phone Network Type:"+strphoneType;
61. info+="\n In Roaming? :"+isRoaming;
62.
63. textView1.setText(info);//displaying the information in the textView
64. }
65.
66.
67. }
AndroidManifest.xml
File: AndroidManifest.xml
Output:
CAMERA
In Android programming, you can use the Camera service to access and interact with the
device's camera hardware to capture photos and record videos. The Android Camera API has
undergone significant changes over the years, with the older Camera API (Camera1) being
replaced by the Camera2 API, which provides more control and flexibility
You must declare the camera permission in your AndroidManifest.xml file and request it at
runtime if your app targets Android 6.0 (API level 23) or higher: You can access the
CameraManager system service to interact with the camera hardware. This service provides
information about available cameras and allows you to open a camera device.
activity_main.xml
Drag one imageview and one button from the pallete, now the xml file will look like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>
Activity class
Let's write the code to capture image using camera and displaying it on the image view.
File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTU
RE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }
Output:
Bluetooth
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:
activity_main.xml
Drag one textview and three buttons from the pallete, now the activity_main.xml file will
like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"
19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>
Provide Permission
File: AndroidManifest.xml
Activity class
Let's write the code to enable, disable and make bluetooth discoverable.
File: MainActivity.java
1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. final TextView out=(TextView)findViewById(R.id.out);
24. final Button button1 = (Button) findViewById(R.id.button1);
25. final Button button2 = (Button) findViewById(R.id.button2);
26. final Button button3 = (Button) findViewById(R.id.button3);
27. final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
28. if (mBluetoothAdapter == null) {
29. out.append("device not supported");
30. }
31. button1.setOnClickListener(new View.OnClickListener() {
32. public void onClick(View v) {
33. if (!mBluetoothAdapter.isEnabled()) {
34. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERAB
LE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_L
ONG);
59.
60. }
61. });
62. }
63.
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.activity_main, menu);
68. return true;
69. }
70.
71. }
WIFI
In Android programming, you can use the Wi-Fi service to manage Wi-Fi connections, scan for
available Wi-Fi networks, and perform various Wi-Fi-related tasks. To work with Wi-Fi in Android,
you need to declare Wi-Fi permissions in your AndroidManifest.xml file You can check the
current state of Wi-Fi (enabled or disabled) using the isWifiEnabled() method: To scan for
available Wi-Fi networks, you can use the startScan() method. This initiates a Wi-Fi scan, and
you can receive the scan results through a broadcast receiver. You can programmatically
connect to a known Wi-Fi network by configuring a WifiConfiguration object and then
calling addNetwork() and enableNetwork()
Android Wifi Example
The android.net.wifi.WifiManager class can be used to manage the wifi connectivity. It
can be used to add network, disable network, scan for access points, disconnect etc.
activity_main.xml
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }
Add Permission in AndroidManifest.xml