Arduino Projects

Android Toggle Button for Automation using Arduino & Bluetooth

Android Toggle Button, Description:

 

Android Toggle Button for Automation using Arduino & Bluetooth– A few months back I uploaded an article on how to create your own android cell phone application to control an LED using Arduino, HC-05 Bluetooth module and an Android cell Phone. For the best understanding, I used only two buttons light ON and light OFF. The two buttons were used to turn ON and turn OFF the led. You can read this article.

 

Android Toggle Button

Using two buttons to control an LED or any other load AC or DC type is good for beginners. But when it comes to the final app development where you need to control multiple loads, this seems very impractical to have two buttons for every load. If you want to control 8 electrical loads you will need 16 buttons. After covering the basics, I decided to make another tutorial focusing on the Android toggle button or switch.

Instead of using two buttons, the same thing can be done by using only one button which is called a toggle switch or a toggle button. Previously I used an LED, so that’s why this time I decided to use a 220Vac light bulb. Later you can increase the number of toggle buttons to control multiple loads. You can download some cool png images of the electrical appliances and use them as the buttons, which you will learn in a minute.

For the practical demonstration, circuit diagram explanation, and programming watch the video given at the end of this article.

Without any further delay let’s get started!!!


Amazon Links:

12v Adaptor:

Arduino Uno

Arduino Nano

Mega 2560:

Bluetooth Module: Hc-05:

1n4007 diode:

10k Resistor:

2n2222 NPN transistor

12V SPDT Relay:

One-Channel Relay Module:

2-channel relay module:

12v SPDT type 4-channel relay Module:

8 channel Relay Module

Other Tools and Components:

Top Arduino Sensors:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Android Toggle Button Circuit Diagram:

Android Toggle Button

The HC-05 or HC-06 Bluetooth Module Tx and Rx pins are connected with the Arduino’s pin number 2 and pin number 3. While the Vcc and GND pins of the Bluetooth module are connected with the Arduino’s 5 Volts and ground.

A 12 volts SPDT “Single Pole and Double Throw” type relay is used to control the AC load. This relay has a total of 5 pins, out of these 5 pins two are the coil pins, common, Normally Open, and normally closed. This relay is controlled by the driver circuit which consists of the Transistor and a 10k ohm resistor. This is a general-purpose NPN transistor. As you can see the emitter is connected with the Ground, the collector is connected with the relay coil pin while the other side of the relay coil is connected with the 12 volts. The base is connected with the Arduino’s pin number 13 through a 10k resistor. A diode is connected across the relay coil, which is used for the back EMF protection. You can use a readymade relay module or you can make the one by yourself.



About HC 05 Bluetooth Module:

The HC-05 Bluetooth Module used in this project is given below.

Android Toggle Button

Android Toggle Button

As you can see clearly in the images above, this Bluetooth module has a total of 6 male headers which are clearly labeled as STATE, RXD, TXD, GND, VCC, and EN. The EN pin has a push button that is used during the time when this module is needed to be entered into the AT commands Mode. I have a very detailed tutorial on how to use the AT commands to change the name of the Bluetooth module and the pairing code. You can watch the following video.

Relay Module with Arduino

Android Toggle Button

As you can see on the left side is the 3 channel relay module, but out of these three relays currently, I am using only one relay which is connected with the Arduino’s pin number 13 and make sure you connect the relay module ground ”blue wire” with the Arduino’s ground. The Bluetooth Module is connected with the Arduino as per the circuit diagram already explained.

Arduino Bluetooth Programming:

#include <SoftwareSerial.h>
SoftwareSerial Blue(2, 3);
long int data;

int relay1 = 13; // DEVICE 1
long int password1 = 92;// light on
long int password2 = 551;// to off

void setup()
{

pinMode(relay1, OUTPUT);
digitalWrite(relay1, LOW);

delay(500);

Serial.begin(9600);
Blue.begin(9600);

}

void loop()
{

while(Blue.available()==0) ;

if(Blue.available()>0)
{
data = Blue.parseInt();
}
delay(400);

if (data == password1)
{

digitalWrite(relay1,HIGH);
Serial.println(“device1 on “);
}

if( data == password2)
{
digitalWrite(relay1,LOW);
Serial.println(“device1 off”);
}

}


Arduino Bluetooth Program explanation:

I started off by including the Software Serial library. The SoftwareSerial library is used to create Serial Ports. You can define multiple Serial Ports. If you are using the Arduino Mega then you don’t need to use the SoftwareSerial library as you know in Arduino Mega we have multiple Serial ports. But when it comes to the Arduino we have only one Serial Port which is available on pin number 0 and pin number 1. As I always say never use the Arduino’s default Serial Port for communication with other devices. The Arduino’s default Serial Port should only be used for debugging purposes. So using the SoftwareSerial library I defined a serial port of the Bluetooth module on pin number 2 and pin number 3 of the Arduino.

The variable data is of the type long integer and is used to store the number sent from the Bluetooth application. This number can be 6 digits long to increase security.

Relay is connected with the Arduino’s pin number 13 which is already explained in the circuit diagram.

long int password1 = 92;

long int password2 = 551;

These are the two passwords that are used to turn ON and turn OFF the load. You can increase the security by using numbers consisting of 6 digits.


In every Arduino or Mega program, we have at least two functions which are the void setup and void loop functions. The void setup function executes only one time when the Arduino or Mega board is turned ON, while the void loop function executes forever until we turn OFF the Board. In the void setup function, the relay is set as the output using the pinMode() function. The relay is turned OFF by using digitalWrite function and finally, the Serial communication is activated.

In the void loop function,

while(Blue.available()==0) ;

If the Arduino has not received any data from the Bluetooth module then simply wait over here.

if(Blue.available()>0)

{

  data = Blue.parseInt();

}

This condition means if the Arduino has received data from the Bluetooth then store the received number in data and compare this with the predefined values and then turn ON and turn OFF the relay accordingly. So that’s all about Arduino programming.



Android Toggle Button app development:

About Bluetooth:

The Android platform provides Bluetooth network stack support, which allows a phone to exchange data wirelessly with other Bluetooth devices. With the Android Bluetooth APIs, the application framework provides access to the Bluetooth features. These APIs allow wireless connection of applications to other Bluetooth devices, allowing point-to-point and wireless multipoint features.

Using the Bluetooth APIs, the following can be achieved by an Android application:

Check for other phones with Bluetooth

For paired Bluetooth devices, ask for a local Bluetooth adapter

Establish channels for RFCOMM

Link to other phones by finding the service

Data transfer from and to other phones

Manage multiple links

This page is dedicated to Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive operations, including streaming and Android phone connectivity. For low-powered Bluetooth devices, Android 4.3 (API level 18) introduces Bluetooth Low Energy API support. See Bluetooth Low Energy for more information. The document defines different models for Bluetooth, including the Health System Profile. It then describes how to use the Android Bluetooth APIs to accomplish the four main tasks required for Bluetooth communication: setting up Bluetooth, identifying devices that are either paired or accessible in the local area, linking devices, and transferring data between devices.


The basics of Bluetooth

To allow Bluetooth devices to transmit data between themselves, they must first use a pairing method to form a communication channel. For incoming connection requests, one device, a discoverable device, makes itself available. Another device uses a service discovery process to find the discoverable device.

The two devices complete a bonding process where they exchange security keys after the discoverable device acknowledges the pairing request. These keys are cached for later use by the devices. The two devices exchange information after the pairing and bonding processes are complete. The device that initiated the pairing request will release the stream that connected it to the discoverable device when the session is complete. Nevertheless, the two devices remain connected, so they can automatically reconnect during a future session so long as they are within each other’s reach and the bond has not been broken by either system.

Bluetooth enabling permission

You must claim two permissions to use Bluetooth features in your software. BLUETOOTH is the first of these. To perform some Bluetooth communication, you need this permission, such as requesting a link, accepting a connection, and transferring data.

ACCESS FINE LOCATION is the other permission to be declared. Your device requires this permission because you can use a Bluetooth scan to collect information about the user’s location. This data can come from the user’s own phones, as well as from Bluetooth beacons used at places like shops and transit facilities.

You will declare the BLUETOOTH ADMIN permission in addition to the BLUETOOTH permission if you want your app to trigger network discovery or modify Bluetooth settings. Many applications only need this permission for local Bluetooth devices to be discovered. Unless the program is a “power manager” which modifies Bluetooth settings upon user request, the other features provided by this permission should not be used. Declare permission(s) for Bluetooth in your manifest application file. Don’t forget to add the Bluetooth permission in manifest.xml before you create the APK file.

xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.bluetoothlight”>

<uses-permission android:name=”android.permission.BLUETOOTH” />

<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN” />

<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:roundIcon=”@mipmap/ic_launcher_round”
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<activity android:name=”.Controlling”></activity>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

Android Toggle Button app development:

First of all, open the Android Studio.

Android Toggle Button

Click on Start a new Android Studio project

Android Toggle Button



While Choose your project form is open.

Select the empty activity and click on the Next button

Android Toggle Button

After you click on the Next button, then configure your project form is opened, over here you set the project name, package name and you can select a directory where you want to store the application. Make sure the language is set to Java. So after you are done then you can click on the Finish button.

Android Toggle Button

Wait for app synchronization

Android Toggle Button

When your project is fully synchronized, as you can see the green dots in the following picture which is an indication that the synchronization is completed and we are ready for the next step.

Android Toggle Button

Before starting app design there are two main classes which is PreferencesActivity.java and

ActivityHelper.java

Now create a java class

Android Toggle Button

Enter name as the ActivityHelper and click ok

Android Toggle Button


And past below code
ActivityHelper.java code

package com.example.lightcontrol;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.preference.PreferenceManager;

public class ActivityHelper {
public static void initialize(Activity activity) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);

String orientation = prefs.getString(“prefOrientation”, “Null”);
if (“Landscape”.equals(orientation)) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (“Portrait”.equals(orientation)) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
}
}

Android Toggle Button

Now create the second java class

Android Toggle Button

Enter class name as the preferrencesActivity and click ok

Android Toggle Button

PreferrencesActivity.java code
package com.example.lightcontrol;

import java.util.Map;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityHelper.initialize(this);
// Using this for compatibility with Android 2.2 devices
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);

if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry());
ActivityHelper.initialize(this);
}

if (pref instanceof EditTextPreference) {
EditTextPreference editPref = (EditTextPreference) pref;
pref.setSummary(editPref.getText());
}
}

@Override
protected void onPause() {

PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}

@Override
protected void onResume() {
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
Map<String, ?> keys = PreferenceManager.getDefaultSharedPreferences(this).getAll();

for (Map.Entry<String, ?> entry : keys.entrySet()) {
// Log.d(“map values”, entry.getKey() + “: ” + entry.getValue().toString());
Preference pref = findPreference(entry.getKey());
if (pref != null) {
pref.setSummary(entry.getValue().toString());
}
}

super.onResume();
}

}

Android Toggle Button


Now we will make a layout for the Search and connect buttons. The search button will be used for searching the Bluetooth module and the connect button will be used to connect with the paird Bluetooth module .

For this click on the small arrow symbol given with the bluetoothlight and find the Res and click on the small arrow to expand it, under the res then click on the layout to expand it and click on the activity_main.xml this will open the design screen.

Android Toggle Button

Now change the layout form constraint layout to linearlayout

Android Toggle Button

As you can see in the picture below.

Android Toggle Button

Now we make another linear layout within the main linearlayout

To create a button in XML we use the button attribute having some property that you can adjust as per your requirements.

Android Toggle Button

To check the design layout for this change from text mode to the design. As you can see at the end of the coding there are two button with captions Design and Text. You can click on the Design button. As you can see the mouse cursor.

Android Toggle Button

It’s a good programming practice to keep checking your design layout as you continue to program. So now we are done with two buttons with captions search and connect. Now we will add the code for the paired device, for this, we use the listview attribute. Click on the Design button to check.

Android Toggle Button

Now open the mainActivity.java class

Android Toggle Button


MainActivity.java code

package com.example.bluetoothlight;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


public class MainActivity extends AppCompatActivity {
    private Button search;
    private Button connect;
    private ListView listView;
    private BluetoothAdapter mBTAdapter;
    private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
    private static final int SETTINGS = 20;
    private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private int mBufferSize = 50000; //Default
    public static final String DEVICE_EXTRA = "com.example.bluetoothlight.SOCKET";
    public static final String DEVICE_UUID = "com.example.bluetoothlight.uuid";
    private static final String DEVICE_LIST = "com.example.bluetoothlight.devicelist";
    private static final String DEVICE_LIST_SELECTED = "com.example.bluetoothlight.devicelistselected";
    public static final String BUFFER_SIZE = "com.example.bluetoothlight.buffersize";
    private static final String TAG = "BlueTest5-MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        search = (Button) findViewById(R.id.search);
        connect = (Button) findViewById(R.id.connect);

        listView = (ListView) findViewById(R.id.listview);

        if (savedInstanceState != null) {
            ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
            if (list != null) {
                initList(list);
                MyAdapter adapter = (MyAdapter) listView.getAdapter();
                int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
                if (selectedIndex != -1) {
                    adapter.setSelectedIndex(selectedIndex);
                    connect.setEnabbulb(true);
                }
            } else {
                initList(new ArrayList<BluetoothDevice>());
            }

        } else {
            initList(new ArrayList<BluetoothDevice>());
        }
        search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mBTAdapter = BluetoothAdapter.getDefaultAdapter();

                if (mBTAdapter == null) {
                    Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
                } else if (!mBTAdapter.isEnabbulb()) {
                    Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBT, BT_ENABLE_REQUEST);
                } else {
                    new SearchDevices().execute();
                }
            }
        });

        connect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                BluetoothDevice device = ((MyAdapter) (listView.getAdapter())).getSelectedItem();
                Intent intent = new Intent(getApplicationContext(), Controlling.class);
                intent.putExtra(DEVICE_EXTRA, device);
                intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
                intent.putExtra(BUFFER_SIZE, mBufferSize);
                startActivity(intent);
            }
        });



    }

    protected void onPause() {
// TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onStop() {
// TODO Auto-generated method stub
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case BT_ENABLE_REQUEST:
                if (resultCode == RESULT_OK) {
                    msg("Bluetooth Enabbulb successfully");
                    new SearchDevices().execute();
                } else {
                    msg("Bluetooth couldn't be enabbulb");
                }

                break;
            case SETTINGS: //If the settings have been updated
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                String uuid = prefs.getString("prefUuid", "Null");
                mDeviceUUID = UUID.fromString(uuid);
                Log.d(TAG, "UUID: " + uuid);
                String bufSize = prefs.getString("prefTextBuffer", "Null");
                mBufferSize = Integer.parseInt(bufSize);

                String orientation = prefs.getString("prefOrientation", "Null");
                Log.d(TAG, "Orientation: " + orientation);
                if (orientation.equals("Landscape")) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else if (orientation.equals("Portrait")) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (orientation.equals("Auto")) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Quick way to call the Toast
     * @param str
     */
    private void msg(String str) {
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }

    /**
     * Initialize the List adapter
     * @param objects
     */
    private void initList(List<BluetoothDevice> objects) {
        final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelectedIndex(position);
                connect.setEnabbulb(true);
            }
        });
    }

    /**
     * Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
     * will show up with this. I didn't see any need to re-build the wheel over here
     * @author ryder
     *
     */
    private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {

        @Override
        protected List<BluetoothDevice> doInBackground(Void... params) {
            Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
            List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
            for (BluetoothDevice device : pairedDevices) {
                listDevices.add(device);
            }
            return listDevices;

        }

        @Override
        protected void onPostExecute(List<BluetoothDevice> listDevices) {
            super.onPostExecute(listDevices);
            if (listDevices.size() > 0) {
                MyAdapter adapter = (MyAdapter) listView.getAdapter();
                adapter.replaceItems(listDevices);
            } else {
                msg("No paired devices found, please pair your serial BT device and try again");
            }
        }

    }

    /**
     * Custom adapter to show the current devices in the list. This is a bit of an overkill for this
     * project, but I figured it would be good learning
     * Most of the code is lifted from somewhere but I can't find the link anymore
     * @author ryder
     *
     */
    private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
        private int selectedIndex;
        private Context context;
        private int selectedColor = Color.parseColor("#abcdef");
        private List<BluetoothDevice> myList;

        public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
            super(ctx, resource, textViewResourceId, objects);
            context = ctx;
            myList = objects;
            selectedIndex = -1;
        }

        public void setSelectedIndex(int position) {
            selectedIndex = position;
            notifyDataSetChanged();
        }

        public BluetoothDevice getSelectedItem() {
            return myList.get(selectedIndex);
        }

        @Override
        public int getCount() {
            return myList.size();
        }

        @Override
        public BluetoothDevice getItem(int position) {
            return myList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private class ViewHolder {
            TextView tv;
        }

        public void replaceItems(List<BluetoothDevice> list) {
            myList = list;
            notifyDataSetChanged();
        }

        public List<BluetoothDevice> getEntireList() {
            return myList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder;
            if (convertView == null) {
                vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
                holder = new ViewHolder();

                holder.tv = (TextView) vi.findViewById(R.id.lstContent);

                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }

            if (selectedIndex != -1 && position == selectedIndex) {
                holder.tv.setBackgroundColor(selectedColor);
            } else {
                holder.tv.setBackgroundColor(Color.WHITE);
            }
            BluetoothDevice device = myList.get(position);
            holder.tv.setText(device.getName() + "\n " + device.getAddress());

            return vi;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.homescreen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(MainActivity.this, PreferencesActivity.class);
                startActivityForResult(intent, SETTINGS);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

To remove  this error just click on the red bulb and select create id value resource

Android Toggle Button

And then click ok

Android Toggle Button



So now you can see the list_item.xml is created

Android Toggle Button

Open list_item.xml file and paste this code
LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:gravity=”center_vertical” >

<!– Defining where should text be placed. You set you text color here –>

<TextView
android:id=”@+id/lstContent”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_margin=”4dip”
android:textSize=”20sp”
android:gravity=”left”
android:padding=”5dp”
android:textColor=”#000000″ />

</LinearLayout>

Now we build the main controlling window, click on the package folder right now

Then New

Then Activity

And click on the Empty Activity

Android Toggle Button

Open  activity_controlling.xml

Android Toggle Button

Now change the layout form constraint layout to RelativeLayout

Android Toggle Button

Open the activity controlling.xml and switch the text type to the design mode

Android Toggle Button

Before creating toggle button first of all copy these two images in drawable folder which is giving below

Android Toggle Button

Android Toggle Button

Android Toggle Button

right click on drawable and click on the android resource file

Android Toggle Button


Resource file name is on_off and press ok and paste the below code
<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:drawable=”@drawable/on” android:state_checked=”true”/>
<item android:drawable=”@drawable/off” android:state_checked=”false”/>

</selector>

Android Toggle Button

Now open activity_controlling.xml and paste the below code
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”
tools:context=”.Controlling”>
<TextView
android:id=”@+id/simpleTextView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Programming Digest”
android:textSize=”40sp”
android:layout_marginTop=”50dp”
android:gravity=”center_horizontal”/>

<ToggleButton
android:layout_width=”150dp”
android:layout_height=”170dp”
android:id=”@+id/on_off”
android:textOff=””
android:textOn=””
android:gravity=”center”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:background=”@drawable/on_off”/>

</RelativeLayout>

Finally, open the Controlling.java

Android Toggle Button

Android Toggle Button

Controlling.java code

package com.example.bluetoothlight;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;

public class Controlling extends Activity {
    private static final String TAG = "BlueTest5-Controlling";
    private int mMaxChars = 50000;//Default//change this to string..........
    private UUID mDeviceUUID;
    private BluetoothSocket mBTSocket;
    private ReadInput mReadThread = null;

    private boolean mIsUserInitiatedDisconnect = false;
    private boolean mIsBluetoothConnected = false;


    private Button mBtnDisconnect;
    private BluetoothDevice mDevice;

    final static String on="92";//on
    final static String off="551";//off


    private ProgressDialog progressDialog;
    ToggleButton On_Off;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_controlling);

        ActivityHelper.initialize(this);
        // mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
        On_Off=(ToggleButton)findViewById(R.id.on_off);




        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
        mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
        mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);

        Log.d(TAG, "Ready");

        On_Off.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){

                    try {
                        mBTSocket.getOutputStream().write(on.getBytes());

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                else{
                    try {
                        mBTSocket.getOutputStream().write(off.getBytes());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        });


    }

    private class ReadInput implements Runnable {

        private boolean bStop = false;
        private Thread t;

        public ReadInput() {
            t = new Thread(this, "Input Thread");
            t.start();
        }

        public boolean isRunning() {
            return t.isAlive();
        }

        @Override
        public void run() {
            InputStream inputStream;

            try {
                inputStream = mBTSocket.getInputStream();
                while (!bStop) {
                    byte[] buffer = new byte[256];
                    if (inputStream.available() > 0) {
                        inputStream.read(buffer);
                        int i = 0;
                        /*
                         * This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
                         */
                        for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
                        }
                        final String strInput = new String(buffer, 0, i);

                        /*
                         * If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
                         */



                    }
                    Thread.sleep(500);
                }
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public void stop() {
            bStop = true;
        }

    }

    private class DisConnectBT extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Void doInBackground(Void... params) {//cant inderstand these dotss

            if (mReadThread != null) {
                mReadThread.stop();
                while (mReadThread.isRunning())
                    ; // Wait until it stops
                mReadThread = null;

            }

            try {
                mBTSocket.close();
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mIsBluetoothConnected = false;
            if (mIsUserInitiatedDisconnect) {
                finish();
            }
        }

    }

    private void msg(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        if (mBTSocket != null && mIsBluetoothConnected) {
            new DisConnectBT().execute();
        }
        Log.d(TAG, "Paused");
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mBTSocket == null || !mIsBluetoothConnected) {
            new ConnectBT().execute();
        }
        Log.d(TAG, "Resumed");
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "Stopped");
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class ConnectBT extends AsyncTask<Void, Void, Void> {
        private boolean mConnectSuccessful = true;

        @Override
        protected void onPreExecute() {

            progressDialog = ProgressDialog.show(Controlling.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554

        }

        @Override
        protected Void doInBackground(Void... devices) {

            try {
                if (mBTSocket == null || !mIsBluetoothConnected) {
                    mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    mBTSocket.connect();
                }
            } catch (IOException e) {
// Unable to connect to device`
                // e.printStackTrace();
                mConnectSuccessful = false;



            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (!mConnectSuccessful) {
                Toast.makeText(getApplicationContext(), "Could not connect to device.Please turn on your Hardware", Toast.LENGTH_LONG).show();
                finish();
            } else {
                msg("Connected to device");
                mIsBluetoothConnected = true;
                mReadThread = new ReadInput(); // Kick off input reader
            }

            progressDialog.dismiss();
        }

    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}

We are done with designing and coding. Now the next step is to create the APK file.


Creating Android Toggle Button application .apk file.

Click on the build menu then hover the mouse on build bundle/(apk) and click on the build apk

Android Toggle Button

And then wait for around one minute depending on your laptop or computer processing speed.

Android Toggle Button

After generating the Android Toggle Button application apk file then click on locate and transfer the app-debug.apk to phone and install

Android Toggle Button



Watch Video Tutorial:

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button