Android

Android Bluetooth

Android Bluetooth

Bluetooth is a very useful functionality to send or receive files between two or more devices. There are several Bluetooth APIs to perform various operations of Bluetooth that include:

  • Scanning of a new Bluetooth device
  • The Pairing of two devices
  • Getting a list of all paired devices

In Android, BluetoothAdapter class is used to implement Bluetooth. The example below demonstrates BluetoothAdapter class to control Bluetooth-related operations:

After creating an application in Android Studio under package com.firstapp.ashulakhwan.greatlearning, you need to modify some files in your project. These files include MainActivity.java, activity_main.xml, and AndroidManifest.xml. The contents of these files after modification are as follows:
MainActivity.java

package com.firstapp.ashulakhwan.greatlearning;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

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

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

import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends Activity  {
   Button btn1,btn2,btn3,btn4;
   private BluetoothAdapter BTAdapter;
   private Set<BluetoothDevice>pairedDevices;
   ListView lstvw;

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

      btn1 = (Button) findViewById(R.id.button);
      btn2 =(Button)findViewById(R.id.button2);
      btn3 =(Button)findViewById(R.id.button3);
      btn4 =(Button)findViewById(R.id.button4);

      BTAdapter = BluetoothAdapter.getDefaultAdapter();
      lstvw = (ListView)findViewById(R.id.listView);
   }

   public void on(View v){
      if (!BA.isEnabled()) {
         Intent btON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(btON, 0);
         Toast.makeText(getApplicationContext(), "Bluetooth is turned on",Toast.LENGTH_LONG).show();
      } else {
         Toast.makeText(getApplicationContext(), "Bluetooth is already turned on", Toast.LENGTH_LONG).show();
      }
   }

   public void off(View v){
      BA.disable();
      Toast.makeText(getApplicationContext(), "Bluetooth is turned off" ,Toast.LENGTH_LONG).show();
   }

    
   public  void visible(View v){
      Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);
   }

    
   public void list(View v){
      pairedDevices = BA.getBondedDevices();
        
      ArrayList list = new ArrayList();

      for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
      Toast.makeText(getApplicationContext(), "The list of Paired Devices", Toast.LENGTH_SHORT).show();

      final ArrayAdapter adapter = new  ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        
      lstvw.setAdapter(adapter);
   }
}

activity_main.xml file will look like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" 
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Android Bluetooth" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="38dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Great Learning"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#bd65f0"
      android:textSize="40dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Turn On BT"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_toStartOf="@+id/imageView"
      android:layout_toLeftOf="@+id/imageView"
      android:clickable="true"
      android:onClick="on" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Make device visible"
      android:onClick="visible"
      android:id="@+id/button2"
      android:layout_alignBottom="@+id/button"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="List of paired devices"
      android:onClick="list"
      android:id="@+id/button3"
      android:layout_below="@+id/imageView"
      android:layout_toRightOf="@+id/imageView"
      android:layout_toEndOf="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Turn OFF BT"
      android:onClick="off"
      android:id="@+id/button4"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <ListView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/listView"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/button"
      android:layout_alignStart="@+id/button"
      android:layout_below="@+id/textView2" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="List of Paired devices:"
      android:id="@+id/textView2"
      android:textColor="#ff34ff06"
      android:textSize="25dp"
      android:layout_below="@+id/button4"
      android:layout_alignLeft="@+id/listView"
      android:layout_alignStart="@+id/listView" />

</RelativeLayout>

The following content is for the file AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.firstapp.ashulakhwan.greatlearning" >
   <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:theme="@style/CustomTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Now, all the modifications of the files are done and you can try running the application on Android Emulator or device to check the results. 

Android - Camera
The Camera is a very useful functionality to capture images. In Android, you can add this functionality to your application by using MediaStore.ACTION_IMAGE_CAPTURE. To understand its working, you can refer to the example shown below:

The first thing you need to do is to create an application under a package com.firstapp.ashulakhwan.greatlearning

The next step is to modify its main file which can be found as src/MainActivity.java. Refer to the following code snippet for this file:


package com.firstapp.ashulakhwan.greatlearning;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {
   public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
   public static final String ALLOW_KEY = "Camera_Allowed";
   public static final String CAMERA_PREF = "Camera_Preference";

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

      if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
         if (getFromPref(this, ALLOW_KEY)) {
            showSettingsAlert();
         } else if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            
            != PackageManager.PERMISSION_GRANTED) {
               
               if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                  Manifest.permission.CAMERA)) {
                  showAlert();
               } else {
                  ActivityCompat.requestPermissions(this,
                     new String[]{Manifest.permission.CAMERA},
                     MY_PERMISSIONS_REQUEST_CAMERA);
               }
            }
      } else {
         openCamera();
      }
      
   }
   public static void saveToPreferences(Context context, String key, Boolean allowed) {
      SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, 
         Context.MODE_PRIVATE);
      SharedPreferences.Editor prefsEditor = myPrefs.edit();
      prefsEditor.putBoolean(key, allowed);
      prefsEditor.commit();
   }
      
   public static Boolean getFromPref(Context context, String key) {
      SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, 
         Context.MODE_PRIVATE);
      return (myPrefs.getBoolean(key, false));
   }
      
   private void showAlert() {
      AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
      alertDialog.setTitle("Alert");
      alertDialog.setMessage("The application requires permission access.");
      
      alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Not allowed",
         new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               finish();
            }
      });
         
      alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
         new DialogInterface.OnClickListener() {
         
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               ActivityCompat.requestPermissions(MainActivity.this,
               new String[]{Manifest.permission.CAMERA},
               MY_PERMISSIONS_REQUEST_CAMERA);
            }
      });
      alertDialog.show();
   }
      
   private void showSettingsAlert() {
      AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
      alertDialog.setTitle("Alert");
      alertDialog.setMessage("The application requires permission access.");
      alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Permission Denied",
         new DialogInterface.OnClickListener() {
         
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
            }
      });
         
      alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
         new DialogInterface.OnClickListener() {
                    
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               startInstalledAppDetailsActivity(MainActivity.this);
            }
      });
         
      alertDialog.show();
   }
      
   @Override
   public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
      switch (requestCode) {
         case MY_PERMISSIONS_REQUEST_CAMERA: {
            for (int i = 0, len = permissions.length; i < len; i++) {
               String permission = permissions[i];
            
               if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                  boolean 
                  showRationale = 
                     ActivityCompat.shouldShowRequestPermissionRationale(
                     this, permission);
                  
                  if (showRationale) {
                     showAlert();
                  } else if (!showRationale) {
             
                     saveToPreferences(MainActivity.this, ALLOW_KEY, true);
                  }
               }
            }
         }         
      }
   }
      
   @Override
   protected void onResume() {
      super.onResume();
   }
      
   public static void startInstalledAppDetailsActivity(final Activity context) {
      if (context == null) {
         return;
      }
         
      final Intent i = new Intent();
      i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
      i.addCategory(Intent.CATEGORY_DEFAULT);
      i.setData(Uri.parse("Package:" + context.getPackageName()));
      i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
      i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
      context.startActivity(i);
   }
      
   private void openCamera() {
      Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
      startActivity(intent);
   }
}

After that, you might need to modify its layout XML file with the name res/layout/activity_main.xml. The content for the files is shown below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
</RelativeLayout>

Next, you will be required to modify the AndroidManifest.xml file:
 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.firstapp.ashulakhwan.greatlearning" >
  <uses-permission android:name="android.permission.CAMERA" />
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/CustomTheme" >
      <activity
         android:name="com.firstapp.ashulakhwan.greatlearning"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
   </application>
</manifest>

In the last step, you need to add permission for the Camera to use on your device and then run the application to verify the results. 

Top course recommendations for you

    Circular Queue
    1 hrs
    Beginner
    3.1K+ Learners
    4.5  (213)
    Python Stack
    2 hrs
    Beginner
    5.8K+ Learners
    4.45  (301)
    AI and Big Data in IOT
    1 hrs
    Intermediate
    10.2K+ Learners
    4.47  (1152)
    Selenium Basics
    1 hrs
    Beginner
    25.4K+ Learners
    4.43  (1917)
    Selenium with Python
    1 hrs
    Beginner
    13.2K+ Learners
    4.44  (819)
    Selenium Projects with Python
    2 hrs
    Intermediate
    8.8K+ Learners
    4.5  (242)
    Java Projects
    1 hrs
    Beginner
    25.2K+ Learners
    4.19  (243)
    JDBC in Java
    1 hrs
    Beginner
    9.3K+ Learners
    4.42  (797)
    Flask Python
    1 hrs
    Beginner
    8.2K+ Learners
    4.38  (456)
    Linked List in Python
    3 hrs
    Beginner
    2.9K+ Learners
    4.55  (62)