How To: Create an Android App With Android Studio to Control LED

480,071

243

166

Published

Introduction: How To: Create an Android App With Android Studio to Control LED

This is a step-by-step tutorial for making an android apk using bluetooth.

Before start coding,

  • Download Android Studio IDE and update Java.
  • Java and C programming skills will help.
  • This tutorial will not explain Java Programming.
  • If you want to code using Eclipse IDE, it is almost the same.
  • The apk will send commands to turn on/turn off a LED and controls the brightness.
  • You can download everything in the last step.

Step 1: Android Studio: New Project

  • Open Android Studio and create a new Project: File > New Project.
  • A pop up Windows will appear. Change the Application Name and Company Name.
  • Click next to choose the target of the application. The default is Android 4.0 (IceCream Sandwich)
  • Click next and choose a Blank Activity.
  • Click next and rename the Activity Name to “DeviceList”.
  • Now click “finish” and the Project will be create.

Step 2: Android: Layout Part 1.

When the build is finished, a “Hello world!” screen will be open. To create the layout of the apk, we need to add:

  • TextView to display some hint to the user;

Click twice the TextView to change the text. A box will appear:
Text = The text to be displayed.
Id = the id of this widget

  • Button to show the paired devices.

Click twice the Button to change the text. A box will appear:
Text = The text to be displayed.
Id = the id of this widget.

  • ListView to show the paired devices;

Now the main activity is finished, you can see that all widget used are shown on Components Tree.

Step 3: Android: .Class Code Part 1.

On the left side there’s a folder called “app “, open it and you’ll see other folder called “java”.
Java folder contains the package of the apk (com.led.led), and all the source code.

  • Open DeviceList class;

Import the followings packages:

import android.widget.Button;
import android.widget.ListView;

Create widgets variables to “call” the widgets used to create the layout:

Button btnPaired;
ListView devicelist;

Initialize the variables.

btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);

Import the following packages:

import java.util.Set;
import java.util.ArrayList;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.AdapterView
import android.widget.AdapterView.OnClickListener
import android.widget.TextView;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

Create variables to control bluetooth:

private BluetoothAdapter myBluetooth = null;
private Set pairedDevices;

Writing a stable code avoids weird erros, so it’s good to check if the device has bluetooth adapter and whether it’s activated.

myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that thedevice has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
} else
{
if (myBluetooth.isEnabled())
{ }
else
{ //Ask to the user turn the bluetooth on Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,1);
}
}

According to Android documents, an Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use-cases:

  • To start an activity:

An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data.

  • To start a service:

A Service is a component that performs operations in the background without a user interface. You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService(). The Intent describes the service to start and carries any necessary data.

  • To deliver a broadcast:

A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().

We need to “listen” when the button is clicked to show paired devices. So OnClickListener Api will handle it

       
btnPaired.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
pairedDevicesList(); //method that will be called
}
});

The PairedDevicesList method:

private void pairedDevicesList()
{ pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList();

if (pairedDevices.size()>0) { for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); }

final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked

}

Step 4: Android: Class Code Part 1.

There is other method called myListClickListener. It allow the ListView to be clicked.

private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
    public void onItemClick (AdapterView av, View v, int arg2, long arg3)
    {
        // Get the device MAC address, the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);
        // Make an intent to start next activity.
        Intent i = new Intent(DeviceList.this, ledControl.class);
        //Change the activity.
        i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
        startActivity(i);
    }
};

Step 5: Android: Layout Part 2.

Go to app > java > com.led.led, Right click, New Activity > Blank Activity

Name it to ledControl and finish. A “Hello world!” screen will be seen.

This second layout will have three buttons, one TextView and a seekbar:

  • Turn On = Turns the LED On;
  • Turn Off = Turns the LED Off;
  • Disconnect = Closes Bluetooth Connection;
  • Indicator;
  • Brightness = control the brightness.

Step 6: Android: .Class Code Part 2.

Open ledControl class and import the following packages:

import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.util.UUID;

Create the following widget variables:

Button btnOn, btnOff, btnDis;
SeekBar brightness;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

We have to initialize the variables and retrieve the bluetooth device address got in DeviceList class.

//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //view of the ledControl layout
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button)findViewById(R.id.button2);
btnOff = (Button)findViewById(R.id.button3);
btnDis = (Button)findViewById(R.id.button4);
brightness = (SeekBar)findViewById(R.id.seekBar);

Let’s create a class to start the connection:

private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{ private boolean ConnectSuccess = true; //if it's here, it's almost connected

@Override protected void onPreExecute() { progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog }

@Override protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background { try { if (btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); btSocket.connect();//start connection } } catch (IOException e) { ConnectSuccess = false;//if the try failed, you can check the exception here } return null; } @Override protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine { super.onPostExecute(result);

if (!ConnectSuccess) { msg("Connection Failed. Is it a SPP Bluetooth? Try again."); finish(); } else { msg("Connected."); isBtConnected = true; } progress.dismiss(); } }

We need to “listen” when the button is clicked to write a command to turn on/turn off the led, disconnect and the control of the brightness.

btnOn.setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { turnOnLed(); //method to turn on } });

btnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { turnOffLed(); //method to turn off } });

btnDis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Disconnect(); //close connection } });

brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser==true) { lumn.setText(String.valueOf(progress)); try { btSocket.getOutputStream().write(String.valueOf(progress).getBytes()); } catch (IOException e) {

} } }

@Override public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override public void onStopTrackingTouch(SeekBar seekBar) {

} });

There is a method called msg(); This method calls Toast.maketext(); There's the method Called Disconnect(); turnOffLed(); and turnOnLed();

private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private void Disconnect()
{ if (btSocket!=null) //If the btSocket is busy { try { btSocket.close(); //close connection } catch (IOException e) { msg("Error");} } finish(); //return to the first layout
}
private void turnOffLed()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("TF".toString().getBytes());
        }
        catch (IOException e)
        {
            msg("Error");
        }
    }
}
private void turnOnLed()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("TO".toString().getBytes());
        }
        catch (IOException e)
        {
            msg("Error");
        }
    }
}

Step 7: Android Manifest

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory.

The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code.

This apk uses Bluetooth Adapter and it is not available in emulator, you must test it in a running device, but before you have to add some users-permissions, otherwise the apk will crash.

In App folder, open manifests > AndroidManifest.xml

  • Add the following code to allow user-permision to use Bluetooth Device
<uses-permission android:name = "android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name = "android.permission.BLUETOOTH"/>
  • Rebuild the project at: Build Menu > Rebuild Project

    Now you can run it in your device.

Step 8: Aruino Code

The arduino C code is very simple, no need to explain it:

char command;
String string;
boolean ledon = false;
#define led 5
char command;
String string; boolean ledon = false; #define led 5 void setup() { Serial.begin(9600); pinMode(led, OUTPUT); } void loop() { if (Serial.available() > 0) {string = "";} while(Serial.available() > 0) {command = ((byte)Serial.read()); if(command == ':') { break; } else { string += command; } delay(1); } if(string == "TO") { ledOn(); ledon = true; } if(string =="TF") { ledOff(); ledon = false; Serial.println(string); //debug } if ((string.toInt()>=0)&&(string.toInt()<=255)) { if (ledon==true) { analogWrite(led, string.toInt()); Serial.println(string); //debug delay(10); } } } void ledOn() { analogWrite(led, 255); delay(10); } void ledOff() { analogWrite(led, 0); delay(10); }

Step 9: Download


The .rar file:

  • Android Studio Project;
  • Arduino .ino;
  • Android Bluetooth Control LED .pdf;

If there's some error, please comment.

Thanks.

4 People Made This Project!

Recommendations

  • Make it Move Contest

    Make it Move Contest
  • Casting Contest

    Casting Contest
  • Microcontroller Contest

    Microcontroller Contest
user

We have a be nice policy.
Please be positive and constructive.

Tips

4 Questions

I've programed the "connectBT" class but I can't see in the whole code where is it called. And It seems that my bluetooth is never connected.

0

in the OnCreate add this :

new ConnectBT().execute(); //Call the class to connect

he didn't mentionned it in the tutorial, but it's in the code he provides below.

I am new to coding. I wrote the code listed in DeviceList.Java screen and experienced many errrors. What am I doing wrong? Code follows.

package com.led.led;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;//import apk packages for widget buttonimport android.widget.Button;import android.widget.ListView;//create widgets variables to "call" the widgets used to create the layout:Button btnPaired; ListView devicelist;//Initialize the variablesbtnPaired = (Button)findViewById(R.id.button); devicelist = (ListView)findViewById(R.id.listView);//import the following packagesimport java.util.Set;import java.util.ArrayList;import android.widget.Toast;import android.widget.ArrayAdapter;import android.widget.AdapterViewimport android.widget.AdapterView.OnClickListenerimport android.widget.TextView;import android.content.Intent;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;//create variables to control bluetooth:private BluetoothAdapter myBluetooth = null;private Set pairedDevices;//check if device has bluetooth adapter and whether it's activated.myBluetooth = BluetoothAdapter.getDefaultAdapter(); if(myBluetooth == null) { //Show a message that the device has no bluetooth adapterToast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show(); //finish apkfinish(); } else{ if (myBluetooth.isEnabled()) { } else{ //Ask to the user turn the bluetooth onIntent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,1); } }//Listen when button is clicked to show paired devicesbtnPaired.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) { pairedDevicesList(); //method that will be called} });private void pairedDevicesList() { pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList(); if (pairedDevices.size()>0) { for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address} } else{ Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); }final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked}private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() {public void onItemClick (AdapterView av, View v, int arg2, long arg3) { // Get the device MAC address, the last 17 chars in the ViewString info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Make an intent to start next activity.Intent i = new Intent(DeviceList.this, ledControl.class); //Change the activity.i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) ActivitystartActivity(i); } }; mport android.bluetooth.BluetoothSocket; import android.content.Intent; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.os.AsyncTask; import java.io.IOException; import java.util.UUID; Button btnOn, btnOff, btnDis; SeekBar brightness; String address = null;private ProgressDialog progress; BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null;private boolean isBtConnected = false;static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//receive the address of the bluetooth deviceIntent newint = getIntent(); address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);//view of the ledControl layoutsetContentView(R.layout.activity_led_control);//call the widgtesbtnOn = (Button)findViewById(R.id.button2); btnOff = (Button)findViewById(R.id.button3); btnDis = (Button)findViewById(R.id.button4); brightness = (SeekBar)findViewById(R.id.seekBar);private class ConnectBT extends AsyncTask // UI thread{ private boolean ConnectSuccess = true; //if it's here, it's almost connected@Overrideprotected void onPreExecute() { progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog} @Overrideprotected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background{ try{ if (btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth deviceBluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's availablebtSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connectionBluetoothAdapter.getDefaultAdapter().cancelDiscovery(); btSocket.connect();//start connection} } catch (IOException e) { ConnectSuccess = false;//if the try failed, you can check the exception here} return null; } @Overrideprotected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine{ super.onPostExecute(result); if (!ConnectSuccess) { msg("Connection Failed. Is it a SPP Bluetooth? Try again."); finish(); } else{ msg("Connected."); isBtConnected = true; } progress.dismiss(); }}btnOn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) { turnOnLed(); //method to turn on} }); btnOff.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) { turnOffLed(); //method to turn off} }); btnDis.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) { Disconnect(); //close connection} }); brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser==true) { lumn.setText(String.valueOf(progress)); try{ btSocket.getOutputStream().write(String.valueOf(progress).getBytes()); } catch (IOException e) { } } }@Overridepublic void onStartTrackingTouch(SeekBar seekBar) { }@Overridepublic void onStopTrackingTouch(SeekBar seekBar) { } });private void msg(String s) { Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); }private void Disconnect() { if (btSocket!=null) //If the btSocket is busy{ try{ btSocket.close(); //close connection} catch (IOException e) { msg("Error");} } finish(); //return to the first layout}private void turnOffLed() { if (btSocket!=null) { try{ btSocket.getOutputStream().write("TF".toString().getBytes()); } catch (IOException e) { msg("Error"); } } }private void turnOnLed() { if (btSocket!=null) { try{ btSocket.getOutputStream().write("TO".toString().getBytes()); } catch (IOException e) { msg("Error"); } } } char command; String string; boolean ledon = false; #define led 5char command; String string; boolean ledon = false; #define led 5void setup() { Serial.begin(9600); pinMode(led, OUTPUT); } void loop() { if (Serial.available() > 0) {string = "";} while(Serial.available() > 0) {command = ((byte)Serial.read()); if(command == ':') { break; } else{ string += command; } delay(1); } if(string == "TO") { ledOn(); ledon = true; } if(string =="TF") { ledOff(); ledon = false; Serial.println(string); //debug} if ((string.toInt()>=0)&&(string.toInt()<=255)) { if (ledon==true) { analogWrite(led, string.toInt()); Serial.println(string); //debugdelay(10); } } } void ledOn() { analogWrite(led, 255); delay(10); } void ledOff() { analogWrite(led, 0); delay(10); }public class DeviceList extends AppCompatActivity { @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_list); }}

0

Hi all, so I've followed this tutorial but have run into bug after bug.

the main ones are that when the app is launched the device list doesn't show up on the screen it just the paired button and the other is that the app no longer asks the user to turn on their Bluetooth, as it did before.

I also have no errors in my code so I'm not sure whats wrong. any help would be appreciated.

where do we download the arduino file to connect it with our app?

166 Comments

put this ( public static String EXTRA_ADDRESS = "device_address"; ) under ( private Set<BluetoothDevices>pairedDevices; )

Hai, I got error message"Connection Failed. Is it a SPP Bluetooth? Try again."

while connecting to device, can you help me why this massage appear. thanks

3 replies

Hi Cxc please could you explaine more in details how the link was usefull because i did not understand how it was solved. thanks

Ok thank you for respon

Please teach me how to solve the "action settings" problems, I copy the identical code from the tutorial but it shows two problems, and it didn't create the menu file automatically I create it by myself please help me

messageImage_1492085463225.jpgmessageImage_1492085484410.jpg
3 replies

Hi, Try modifying copying the "strings.xml" file, can be found in the folder "values".

Thanks man. I am really appreciate.

You need to take a break and every problem will be sloved!
Okay,bro?

I just install the app in my Huawei mobile phone,but it suddenly closes as soon as opens,any body can help

1 reply

Hi, were you able to fix the problem? I'm also having the same issue on mz huawei phone.

Hey Every one.. All the things work well but when click on LedOn button it responds nothing, i have tried like this;

public void turnOnLed(View view)

{

if (btSocket!=null)

{ try

{

btSocket.getOutputStream().write("TO".toString().getBytes()); Toast.makeText(getApplicationContext(), "Led off", Toast.LENGTH_SHORT).show();

}

catch (IOException e) { msg("Error"); }

}

else

{

msg("Operation Failed"); }

}

This is executing the bold/else body.. Plz any help me for this issue. thanks.

1 reply

Hi, have you solve your issue?

Sir, may i consult you?

What do you need for the Arduino
board itself to be able to connect via Bluetooth? You never explained how to build the Auduino circuit!

Great tutorial thanks so much for posting! However, like some others I have an issue where the Bluetooth stops responding after a while. It must be an issue with the android app as when using a terminal application it does not drop the link. Does anyone know what could be causing that?