You are on page 1of 25

Chap-7.

Peer to peer to communication


Accessing Telephony Hardware:
-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. A mobile handset is a state machine. It
keeps track of the mobile radio reports, provides audible call state indications to the user,
and enables the user to provide inputs which modifies that state.
In android environment, the android.telephony package contains a set of classes. These
classes can be used by any application to monitor the state of Android’s mobile network
connection. This package also contains classes for locating a device via the intelligent usage
of mobile network. It also offers utility classes for parsing, formatting, and managing phone
numbers. To be honest there is no architectural benefit to locating those classes in this
package. Telephony package focuses on retrieving information and giving users an interface
to edit telephone numbers.

write the code to display the information about the telephony services.

1. package com.javatpoint.telephonymanager;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.content.Context;  
5. import android.telephony.TelephonyManager;  
6. import android.view.Menu;  
7. import android.widget.TextView;   
8. public class MainActivity extends Activity {  
9.    TextView textView1;  
10.     @Override  
11.     protected void onCreate(Bundle savedInstanceState) {  
12.         super.onCreate(savedInstanceState);  
13.         setContentView(R.layout.activity_main);  
14.           
15.         textView1=(TextView)findViewById(R.id.textView1);  
16.          
17.         //Get the instance of TelephonyManager  
18.         TelephonyManager  tm=(TelephonyManager)getSystemService(Context.TELEPH
ONY_SERVICE);  
19.         //Calling the methods of TelephonyManager the returns the information  
20.         String IMEINumber=tm.getDeviceId();  
21.         String subscriberID=tm.getDeviceId();  
22.         String SIMSerialNumber=tm.getSimSerialNumber();  
23.         String networkCountryISO=tm.getNetworkCountryIso();  
24.         String SIMCountryISO=tm.getSimCountryIso();  
25.         String softwareVersion=tm.getDeviceSoftwareVersion();  
26.         String voiceMailNumber=tm.getVoiceMailNumber();  
27.           
28.         //Get the phone type  
29.         String strphoneType="";  
30.           
31.         int phoneType=tm.getPhoneType();  
32.   
33.         switch (phoneType)   
34.         {  
35.                 case (TelephonyManager.PHONE_TYPE_CDMA):  
36.                            strphoneType="CDMA";  
37.                                break;  
38.                 case (TelephonyManager.PHONE_TYPE_GSM):   
39.                            strphoneType="GSM";                
40.                                break;  
41.                 case (TelephonyManager.PHONE_TYPE_NONE):  
42.                             strphoneType="NONE";                
43.                                 break;  
44.          }  
45.         //getting information if phone is in roaming  
46.         boolean isRoaming=tm.isNetworkRoaming();  
47.           
48.         String info="Phone Details:\n";  
49.         info+="\n IMEI Number:"+IMEINumber;  
50.         info+="\n SubscriberID:"+subscriberID;  
51.         info+="\n Sim Serial Number:"+SIMSerialNumber;  
52.         info+="\n Network Country ISO:"+networkCountryISO;  
53.         info+="\n SIM Country ISO:"+SIMCountryISO;  
54.         info+="\n Software Version:"+softwareVersion;  
55.         info+="\n Voice Mail Number:"+voiceMailNumber;  
56.         info+="\n Phone Network Type:"+strphoneType;  
57.         info+="\n In Roaming? :"+isRoaming;  
58.           
59.         textView1.setText(info);//displaying the information in the textView  
60.     }  
61.   
62.      
63. }  
Introducing Android Instant Messaging: -
Instant messaging is a set of communication technologies used for text-based
communication between two or more participants over the internet. Im allows effective and
efficient communication, allowing immediate receipt of acknowledgment or reply. In the
company, colleagues can send and reply instant message in real time without face to face,
meanwhile the work report can be shared during the instant chat session; it can make a
virtual conference without get all the related people together in a physical meeting room.
Using instant messages for interoffice communication is quicker than phone calls or emails.
More than one person can chat at the same time. This is a huge benefit of using an instant
messenger. Instead of relying on a conference call or copying others on an email message,
everybody can join and have a discussion in real time. Better than email, if you truly want
to communicate instantly you need to consider all your options.

Example:

1. Facebook
2. What’s App
3. Yahoo
4. Gmail
5. Hike
6. Instagram
7. Snapchat

Features:-

1. Stay connected across all messaging systems


2. Tablet-optimized UI
3. Free instant messaging
4. Off-the-Record Messaging
5. Widget, avatars, emoticons, custom statuses and message templates
6. User interface in English, Spanish, German

GTalk Service: Using, binding & Making connection:-


Google Talk Service Monitor in android mobile phones will monitor Google Talk host address
& port, your Google JID, your Device ID, GTalk connection status , your connection
history,your current GTalk presence (available, idle or invisible) and many other things like
GTalk heartbeat status.

 IGTalkService Is used to create, access, and manage GTalk connections.


 IGTalkConnection A GTalk Connection represents a persistent socket connection between the
device and the server it’s connecting to. The GTalk Service creates a default connection upon
start-up that you can access by calling getDefaultConnection on the GTalk Service object.

Binding to the GTalk Service:


To use the GTalk Service, it must be bound to your application component using bind Service.

The bindService method accepts two input parameters, an Intent, which specifi es a component to
bind to, and a ServiceConnection implementation. The following skeleton code demonstrates the
pattern used to bind to the GTalk service:

IGTalkService gtalkService; private void bindGTalk()

Intent i = new Intent();

i.setComponent(GTalkServiceConstants.GTALK_SERVICE_COMPONENT);

bindService(i, gTalkConnection, 0);

private ServiceConnection gTalkConnection = new ServiceConnection()

// When the service connects, get the default GTalk Session

public void onServiceConnected(ComponentName className, IBinder service)

gtalkService = IGTalkService.Stub.asInterface(service);

// If the service disconnects public void onServiceDisconnected(ComponentName className)

gtalkService = null;

};
A bound GTalk Service represents a connection between your application and the GTalk Service
APIs.

Making a GTalk Connection and Starting an IM Session:


A GTalk Connection represents a conduit between the device and a GTalk server. An IM Session is
the message pathway used to handle all the instant message traffic; all the instant messages for a
given session flow through this pipe.

private IGTalkConnection gTalkConnection = null;

private IImSession imSession = null;

private ServiceConnection gTalkServiceConnection = new ServiceConnection()

{ // When the service connects, get the default GTalk session.

public void onServiceConnected(ComponentName className, IBinder service)

IGTalkService gtalkService = IGTalkService.Stub.asInterface(service);

Try

gTalkConnection = gtalkService.getDefaultConnection();

imSession = gTalkConnection.getDefaultImSession();

catch (RemoteException e) { }

// When the service disconnects, clear the GTalk session.

public void onServiceDisconnected(ComponentName className)

gTalkConnection = null; imSession = null;

}
};

Managing Chat Sessions: -


Chat Sessions are created within IM Sessions and are used to manage and participate in person-to-
person chats and chat rooms. All text-based instant message chats are handled using the
IChatSession interface, which offers methods for sending text or data messages and inviting new
participants into a chat.

You can attach a Chat Listener to a Chat Session to listen to the messages associated with it.
Handling Chat Sessions is particularly useful for integrating text messaging within your own
applications. Using a Chat Session, you can create a chat room for multiplayer games, or integrate
person-toperson messaging within a mobile social networking application.

Managing Group Chat Sessions: You can get a list of participants in a Chat Session using the
getParticipants method. You can also send text or data messages to each chat member as you would
in a normal chat, as well as invite new members using inviteContact. The leave method lets you exit
a chat room and end the session.

IChatListener groupChatListener = new IChatListener.Stub()

// Fired when a one-to-one chat becomes a group chat.

public void convertedToGroupChat(String oldJid, String groupChatRoom, long groupId) throws


RemoteException

// TODO Notify user that the conversation is now a group chat

// Fired when a new person joins a chat room

public void participantJoined(String groupChatRoom, String nickname) throws RemoteException

// TODO Notify user that a new participant has joined the conversation.

}
// Fired when a participant leaves a chat room.

public void participantLeft(String groupChatRoom, String nickname) throws RemoteException

// TODO Notify user a chat participant left.

// Fired when the group chat is closed

public void chatClosed(String groupChatRoom) throws RemoteException

// TODO Close the chat.

public void chatRead(String arg0) throws RemoteException { }

public void newMessageReceived(String from, String body) { }

};

Sending and receiving Data messages: -


Sending SMS Data messages
So lets start with the sender AndroidManifest.xml. I recommend you open up the sample code, as I will
be highlighting the key parts on this page.
 <uses-permission android:name="android.permission.SEND_SMS" />

The uses-permission tag will allow the application to send SMS messages. Sending SMS message with
the application will potentially incur additional cost on the user’s end.
Indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow
the application to install or not.

SendActivity Class:

private void sendSMS()
  {

    PendingIntent sent = this.createPendingResult(SENT, new Intent(),
PendingIntent.FLAG_UPDATE_CURRENT);
    String messageText = _message.getText().toString();

    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendDataMessage(_phoneNumber.getText().toString(), null,
SMS_PORT, messageText.getBytes(), sent, null);
  }

To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly
instantiate this class; instead you will call the getDefault() static method to obtain
an SmsManager object. The sendDataMessage() method sends the SMS message with a PendingIntent.
The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending
the message, you can use a PendingIntent object to update the current activity, and onActivityResult will
be triggered.

 @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent
data)
  {
    String toast = null;
    switch (requestCode)
    {
      case SENT :
        switch (resultCode)
        {
          case RESULT_OK :
            toast = "OK";
            break;
          case SmsManager.RESULT_ERROR_GENERIC_FAILURE :
            toast = "Generic Failure";
            break;
          case SmsManager.RESULT_ERROR_RADIO_OFF :
            toast = "Radio Off";
            break;
          case SmsManager.RESULT_ERROR_NULL_PDU :
            toast = "Null Pdu";
            break;
        }
        break;
    }

    if (toast != null)
    {
      Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
    }
}

Receiving SMS Data messages: -


Besides sending SMS messages, you can also intercept incoming SMS messages using
a BroadcastReceiver object.
To see how to receive SMS messages from within your Android application, lets look at
the AndroidManifest.xml file within our receiver sample code.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
 <uses-permission android:name="android.permission.BROADCAST_SMS" />
 <uses-permission android:name="android.permission.READ_SMS" />

The uses-permission tags will allow the application to receive and read SMS messages. Lets create a
class that extends the BroadcastReceiver class and override the onReceive() method:

@Override
  public void onReceive(Context context, Intent intent)
  {
    Bundle bundle = intent.getExtras();

    String recMsgString = "";
    String fromAddress = "";

    SmsMessage recMsg = null;
    byte[] data = null;

    if (bundle != null)
    {
      //---retrieve the SMS message received---
      Object[] pdus = (Object[]) bundle.get("pdus");
      for (int i = 0; i < pdus.length; i++)
      {
        recMsg = SmsMessage.createFromPdu((byte[]) pdus[i]);

        try
        {
          data = recMsg.getUserData();
        }
        catch (Exception e)
        {

        }
        if (data != null)
        {
          for (int index = 0; index < data.length; ++index)
          {
            recMsgString += Character.toString((char) data[index]);
          }
        }

        fromAddress = recMsg.getOriginatingAddress();
      }
    }

    Intent result = new Intent(context, ReceiveActivity.class);


    result.putExtra(ReceiveActivity.MESSAGE, "Received SMS from
" + fromAddress + ": " + recMsgString);
    result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(result);
  }

When SMS messages are received, the onReceive() method will be invoked. The SMS message is
contained and attached to the Intent object via a Bundle object.
Introducing SMS: - In Android, you can use SmsManager API or devices Built-in SMS
application to send SMS's. In this tutorial, we shows you two basic examples to send SMS message −
SmsManager API
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Built-in SMS application


Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Using, sending & receiving SMS Messages:

package com.example.tutorialspoint;

import android.Manifest;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.app.Activity;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.telephony.SmsManager;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends Activity {

private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;

Button sendBtn;

EditText txtphoneNo;

EditText txtMessage;

String phoneNo;

String message;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

sendBtn = (Button) findViewById(R.id.btnSendSMS);

txtphoneNo = (EditText) findViewById(R.id.editText);

txtMessage = (EditText) findViewById(R.id.editText2);

sendBtn.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

sendSMSMessage();

});

}
protected void sendSMSMessage() {

phoneNo = txtphoneNo.getText().toString();

message = txtMessage.getText().toString();

if (ContextCompat.checkSelfPermission(this,

Manifest.permission.SEND_SMS)

!= PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(this,

Manifest.permission.SEND_SMS)) {

} else {

ActivityCompat.requestPermissions(this,

new String[]{Manifest.permission.SEND_SMS},

MY_PERMISSIONS_REQUEST_SEND_SMS);

@Override

public void onRequestPermissionsResult(int requestCode,String permissions[], int[]


grantResults) {

switch (requestCode) {

case MY_PERMISSIONS_REQUEST_SEND_SMS: {

if (grantResults.length > 0

&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(phoneNo, null, message, null, null);

Toast.makeText(getApplicationContext(), "SMS sent.",

Toast.LENGTH_LONG).show();
} else {

Toast.makeText(getApplicationContext(),

"SMS faild, please try again.", Toast.LENGTH_LONG).show();

return;

Chap-8. Accessing Android Hardware

Audio, Video and Using the camera: -


 For audio/video files, you need to create a new folder/directory called ‘raw’ inside ‘res’ directory
and place your files inside the ‘raw’ directory

 Or you can access files from your SD card or phone memory for playing, if you don't want to
include them in your application

Using Audio Example:


 Let’s suppose we want to play a small beep sound whenever a button is
pressed/clicked/touched in our App
 Create a blank project
 First you need to create a new directory named ‘raw’ inside ‘res’ directory
(yourprojectname/res/raw)
 Now place a sound clip inside this newly created directory
 Open you layout.xml file and insert a Button control
 Open you main activity (.java file), and place the following lines of code inside
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
MediaPlayer p = MediaPlayer.create(Main.this, R.raw.abc.mp3);
p.start();
}
});
* abc.mp3 is the name of the audio clip

Using Video Example:

 If we want to play a video file saved in our SD card or phone memory, we need a video player
control
 Create a blank project
 Place a Video View control on your main layout
 Edit main activity (.java file) to include the following lines of code

VideoView v = (VideoView) findViewById(R.id.videoView1);

v.setVideoPath("/sdcard/abc.mp4");

v.start();

// include the following line if you want your video view control to have play, pause, FF controls

v.setMediaController(new MediaController(this));

* abc.mp4 is the name of the video file present in the SD

Using Camera Example:

 For access or use camera, you need to access/communicate directly with the built-in camera
App
 Your App will communicate with camera App and get image/video captured/recorded and
then you can use it
 Create a blank project, in this example we’ll capture an image and then display it on our
main activity
 Edit the layout.xml to insert a Button and an Image View control
 Edit the main activity (.java file) and place the following lines of code in it

iv = (ImageView) findViewById(R.id.imageView1);

Button b = (Button) findViewById(R.id.button1);

b.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(i, 0);

});

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

Bitmap bmap = (Bitmap) data.getExtras().get("data");

iv.setImageBitmap(bmap);

* An intent is needed to communicate with the camera App. The results are expected
(image/video file), so the start activity method is called for results. The bitmap image returned is
then displayed using Image View control
Introducing Sensor Manager:
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental conditions. The android platform supports three broad categories of sensors .

 Motion Sensors

 Environmental sensors

 Position sensors

Some of the sensors are hardware based and some are software based sensors. Whatever the
sensor is, android allows us to get the raw data from these sensors and use it in our application.
For this android provides us with some classes.

Android provides SensorManager and Sensor classes to use the sensors in our application. In
order to use sensors, first thing you need to do is to instantiate the object of SensorManager
class.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.TextView;

import java.util.List;
import android.hardware.Sensor;

import android.hardware.SensorManager;

public class MainActivity extends Activity {

TextView tv1=null;

private SensorManager mSensorManager;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tv1 = (TextView) findViewById(R.id.textView2);

tv1.setVisibility(View.GONE);

mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);

for (int i = 1; i < mList.size(); i++) {

tv1.setVisibility(View.VISIBLE);

tv1.append("\n" + mList.get(i).getName() + "\n" + mList.get(i).getVendor() +


"\n" + mList.get(i).getVersion());

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

return super.onOptionsItemSelected(item);

Using Bluetooth:
Among many ways, Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.

 Scan for other Bluetooth devices


 Get a list of paired devices
 Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of
this calling by calling the static method getDefaultAdapter ().

Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.

Sr.No Method & description

1
enable():-This method enables the adapter if not enabled

2 isEnabled():-This method returns true if adapter is enabled

3 disable():-This method disables the adapter

4 getName():-This method returns the name of the Bluetooth adapter

5 setName(String name):-This method changes the Bluetooth name

6 getState():-This method returns the current state of the Bluetooth Adapter.

startDiscovery():-This method starts the discovery process of the


7
Bluetooth for 120 seconds.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.content.Intent;

import android.os.Bundle;
import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.ListView;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.Set;

public class MainActivity extends Activity {

Button b1,b2,b3,b4;

private BluetoothAdapter BA;

private Set<BluetoothDevice>pairedDevices;

ListView lv;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);

b2=(Button)findViewById(R.id.button2);

b3=(Button)findViewById(R.id.button3);

b4=(Button)findViewById(R.id.button4);

BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);

public void on(View v){

if (!BA.isEnabled()) {

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(turnOn, 0);

Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();

} else {

Toast.makeText(getApplicationContext(), "Already on",


Toast.LENGTH_LONG).show();

public void off(View v){

BA.disable();

Toast.makeText(getApplicationContext(), "Turned off"


,Toast.LENGTH_LONG).show();

public void visible(View v){

Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

startActivityForResult(getVisible, 0);

public void list(View v){


pairedDevices = BA.getBondedDevices();

ArrayList list = new ArrayList();

for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());

Toast.makeText(getApplicationContext(), "Showing Paired


Devices",Toast.LENGTH_SHORT).show();

final ArrayAdapter adapter = new


ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);

Manage network and Wi-Fi connections:


This lesson describes how to write applications that have fine-grained control over their usage of
network resources. If your application performs a lot of network operations, you should provide user
settings that allow users to control your app’s data habits, such as how often your app syncs data,
whether to perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, and so
on. With these controls available to them, users are much less likely to disable your app’s access to
background data when they approach their limits, because they can instead precisely control how much
data your app uses.

A device can have various types of network connections. This lesson focuses on using either a Wi-Fi or a
mobile network connection. For the full list of possible network types, see ConnectivityManager.

Wi-Fi is typically faster. Also, mobile data is often metered, which can get expensive. A common strategy
for apps is to only fetch large data if a Wi-Fi network is available.

Android - Wi-Fi
Android allows applications to access to view the access the state of the wireless connections at very
low level. Application can access almost all the information of a wifi connection .
The information that an application can access includes connected network's link speed,IP address,
negotiation state, other networks information. Applications can also scan, add, save, terminate and
initiate Wi-Fi connections.

Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this
class by calling getSystemServicemethod. Its syntax is given below −

Sr.N Method & Description


o

1
addNetwork(WifiConfiguration config):-This method add a new network
description to the set of configured networks.

2
createWifiLock(String tag):-This method creates a new WifiLock.

3
disconnect():-This method disassociate from the currently active access
point.

4
enableNetwork(int netId, boolean disableOthers):-This method allow a
previously configured network to be associated with.

5
getWifiState():-This method gets the Wi-Fi enabled state

6
isWifiEnabled():-This method return whether Wi-Fi is enabled or disabled.

7
setWifiEnabled(boolean enabled):-This method enable or disable Wi-Fi.

8
updateNetwork(WifiConfiguration config):-This method update the
network description of an existing configured network.

package com.example.sairamkrishna.myapplication;

import android.net.wifi.WifiManager;

import android.os.Bundle;

import android.app.Activity;
import android.content.Context;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity {

Button enableButton,disableButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

enableButton=(Button)findViewById(R.id.button1);

disableButton=(Button)findViewById(R.id.button2);

enableButton.setOnClickListener(new OnClickListener(){

public void onClick(View v){

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

wifi.setWifiEnabled(true);

});

disableButton.setOnClickListener(new OnClickListener(){

public void onClick(View v){

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

wifi.setWifiEnabled(false);

});

You might also like