Arduino Bluetooth controlling application development using Android Studio
Android Application development for Bluetooth controlling
Description:
Arduino Bluetooth controlling application development using android studio- in this article, I am going to show you to design and develop an android application that controls anything over Bluetooth. in this article, I am covering only the android side. for Arduino programming and circuit diagram visit my article, Arduino Bluetooth controlling system for Home Automation using Arduino & Bluetooth
Arduino Bluetooth controlling Application Designing and Development:
First of all, open the Android Studio.
Click on Start a new Android Studio project
While Choose your project form is open.
Select the empty activity and click on the Next 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.
Wait for app synchronization
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.
Before starting app design there are two main classes which are PreferencesActivity.java and ActivityHelper.java
Now create a java class
Enter name as the ActivityHelper and click ok
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);
}
}
}
Now create the second java class
Enter the class name as the preferrencesActivity and click ok
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();
}
}
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 paired 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.
Now change the layout form constraint layout to linearlayout
As you can see in the picture below.
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.
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.
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.Copy the below code in your activity_main.xml
activity_main.xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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”
android:orientation=”vertical”
tools:context=”.MainActivity”>
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:layout_marginTop=”20dp”>
<Button
android:id=”@+id/search”
android:layout_width=”wrap_content”
android:layout_height=”match_parent”
android:layout_marginLeft=”90dp”
android:text=”Search”/>
<Button
android:id=”@+id/connect”
android:layout_width=”wrap_content”
android:layout_height=”match_parent”
android:text=”Connect”/>
</LinearLayout>
<ListView
android:id=”@+id/listview”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
</ListView>
</LinearLayout>
Now open the mainActivity.java class and paste the below code
MainActivity.java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
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 And then click ok
So now you can see the list_item.xml is created
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
Open activity_controlling.xml
‘
Now change the layout form constraint layout to RelativeLayout
Open the activity controlling.xml and switch the text type to the design mode
Before creating a toggle button first of all copy these two images in drawable folder which is giving below
right-click on drawable and click on the android resource file
The resource file name is on_off and press ok and paste the below code
1 2 3 4 5 6 |
<?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> |
Now open activity_controlling.xml and paste the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?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 file
and paste the below in your Controlling.java file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
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 programming. Now the next step is to create the APK file.
Creating Arduino Bluetooth controlling application .apk file:
Click on the Build menu then hover the mouse on build bundle/(apk) and click on the build apk
And then wait for around one minute depending on your laptop or computer processing speed.
After generating the apk file then click on locate and transfer the app-debug.apk to the phone and install
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?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> |
Download apk file: home automation app