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

612,302

291

192

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

About: Dude!

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.

5 People Made This Project!

Recommendations

  • Box Challenge

    Box Challenge
  • Explore Science Challenge

    Explore Science Challenge
  • Toys & Games Contest

    Toys & Games Contest

192 Comments

0
oladunk321
oladunk321

5 months ago

Nice project.
How can I import this Android App into a newer version of Android Studio ?
I'm using version 3.6.3 and during build I get a lot of error messages. Too many to list here.
This app is from 2015. Should I find an older version of AS ? Or is it an easier way to import the App ? Any hints out there ?

0
dcreates
dcreates

Reply 5 months ago

Did you made it?

0
oladunk321
oladunk321

Reply 5 months ago

I found the old version 1.1.0 the author used to build the project.
It is called android-studio-bundle-135.1740770 , try using duckduckgo.com as search engine.

0
dcreates
dcreates

Reply 4 months ago

I kind of made the app. But I'm still stuck.

0
oladunk321
oladunk321

Reply 4 months ago

Did you make it to build without errors ? Can you transfer the app to a phone ?
Where are you stuck ?

0
oladunk321
oladunk321

Reply 5 months ago

Hi, I gave up. Have very little experience in Android Studio and the project is 5 years old. Suspect there are too many differences between the versions.
The oldest Android Studio I could find was 2.3.2 or something from 2017.
I will keep looking on Google for a newer project that can work or ask somebody on a Android Studio forum for assistance.I'm sure this can be solved with the right expertise.I'm just a hobby programmer trying to learn Java.

0
Dimo Wibowo
Dimo Wibowo

1 year ago

Thanks your article is usefull

0
dcreates
dcreates

Reply 5 months ago

Did you made it?

0
th.kiet1004
th.kiet1004

Question 5 months ago

when i use gradle for link: FPA13UGILJWNZUL/LED/gradle/wrapper .
It say: The version of Gradle you connect to does not support that method.
To resolve the problem you can change/upgrade the target version of Gradle you connect to.
But when i use gradle for newest version 6.7.1. it say gradle 2.2 support this method and i need to use gradle/wrapper.
excuse for my english

0
dcreates
dcreates

Answer 5 months ago

Can you please share your project.

0
matejhilmer
matejhilmer

8 months ago

Hi, your project looks great and I would like to learn some Java by tweaking your code, but upon trying to sync with Gradle files, I'm getting this error:

"Unsupported method: BaseConfig.getApplicationIdSuffix().
The version of Gradle you connect to does not support that method.
To resolve the problem you can change/upgrade the target version of Gradle you connect to.
Alternatively, you can ignore this exception and read other information from the model."

I'm completely new to Java and Android Studio - I only know Arduino so far. Can you help me with this bit? Thanks!

0
ororso135055
ororso135055

11 months ago

i am using hm10 Bluetooth module, app doesn't allow to connect to Bluetooth.
Showing the toast Try again.
What should i do now???????
Help.

KakaoTalk_20200716_101345189.jpg
0
mrwolfe
mrwolfe

1 year ago

Hi. Great tutorial. do you have any plans to update this for Android Studio 3.0+? the user interface for the later versions of AS is quite different. That said, I went through the "getting started" tutorial in AS, and I think I can now make this work in the new version.

0
ManuelR47
ManuelR47

2 years ago

Excellent tutorial!, I did use of that code for school and made some modifications to that code for an HC-06 with AES encryption and works fine. Thanks for share the knowledge.
Your name is on the "Thank you page".
=D

0
syus
syus

2 years ago

I got an error after clicking on paired devices "Unfortunately, Led Controller has stopped". Can you tell me why?

0
FranciscoG170
FranciscoG170

Question 2 years ago

Thanks so much for your help. I have a question, if I use a Bluetooth module LE HM-10, do I have to make any changes? Thank you

0
Bedo0o
Bedo0o

2 years ago

Thanks so much for your effort
your help is benefit me in my graduation project thanks soo much

2
Mücahit AlperK
Mücahit AlperK

2 years ago

Can we make autoconnection to bluetooth module when app started?

0
GayathiriB
GayathiriB

Question 2 years ago on Introduction

Can we use the same code for buzzer in the place of led.?? But no output
Reply soon pls

0
Haseebwarriach
Haseebwarriach

3 years ago

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