Share Images With Bluetooth Programmatically Android What Activity to Launch

To develop an Android application making utilise of data transfers via Bluetooth (BT), one would logically start at the Android Programmer'southward Bluetooth page, where all the required steps are described in details: device discovery, pairing, client/server sockets, RFCOMM channels, etc.

Just earlier jumping into sockets and threads programming just to perform a bones BT operation, permit's consider a simpler alternative, based on one of Android'due south most important features: the ability for a given application to send the user to another one, which, in this example, would be the device's default BT application. Doing so will have the Android Os itself do all the low-level work for us.

First things first, a bit of defensive programming:

import android.bluetooth.BluetoothAdapter; //... // inside method // Check if bluetooth is supported BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();  if (btAdapter == null) {    // Device does non back up Bluetooth    // Inform user that we're washed.     	  }

The higher up is the outset check we demand to perform. Washed that, let'south see how he can start BT from within our ain application.

In a previous post on SMS programming, we talked about implicit intents, which basically allow united states to specify the activity nosotros would similar the organisation to handle for us. Android will and so display all the activities that are able to complete the activeness we want, in a chooser list.  Here's an instance:

// bring up Android chooser Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plainly"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file_to_transfer) ); //... startActivity(intent);

In the code snippet above, we are letting the Android organisation know that nosotros intend to transport a text file. The system then displays all installed applications capable of treatment that activity:

chooser

We can see that the BT awarding is among those handlers. We could of grade let the user pick that application from the listing and be done with it.  But if we feel  we should be a tad more user-friendly, we need to get further and start the application ourselves, instead of simply displaying information technology in a midst of other unnecessary options…But how?

Ane way to do that would be to use Android'southward PackageManager this way:

//listing of apps that can handle our intent PackageManager pm = getPackageManager(); List appsList = pm.queryIntentActivities( intent, 0);  if(appsList.size() > 0 {    // proceed }

The to a higher place PackageManager method returns the list we saw earlier of all activities susceptible to handle our file transfer intent, in the form of a listing of ResolveInfo objects that encapsulate information nosotros need:

//select bluetooth String packageName = null; String className = null; boolean found = faux;  for(ResolveInfo info: appsList){   packageName = info.activityInfo.packageName;   if( packageName.equals("com.android.bluetooth")){      className = info.activityInfo.proper name;      plant = true;      intermission;// institute   } } if(! found){   Toast.makeText(this, R.string.blu_notfound_inlist,                  Toast.LENGTH_SHORT).evidence();   // exit }

We now accept the necessary information to showtime BT ourselves:

//set our intent to launch Bluetooth intent.setClassName(packageName, className); startActivity(intent);

What we did was to utilise the package and its corresponding class retrieved earlier. Since nosotros are a curious bunch, nosotros may wonder what the form proper name for the "com.android.bluetooth" package is. This is what we would get if we were to impress it out: com.broadcom.bt.app.opp.OppLauncherActivityOPP stands for Object Push Contour, and is the Android component allowing to wirelessly share files.

All fine and slap-up, simply in order for all the above lawmaking to exist of any use, BT doesn't only demand to be supported by the device, but also enabled by the user. So i of the first things we desire to do, is to ask the user to enable BT for the time we deem necessary (hither, 300 seconds):

import android.bluetooth.BluetoothAdapter; //... // duration that the device is discoverable individual static concluding int DISCOVER_DURATION = 300;  // our request code (must be greater than zero) individual static concluding int REQUEST_BLU = 1;  //...  public void enableBlu(){ // enable device discovery - this will automatically enable Bluetooth Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,                             DISCOVER_DURATION );  startActivityForResult(discoveryIntent, REQUEST_BLU); }

Once nosotros specify that we want to become a issue back from our action with startActivityForResult, the following enabling dialog is presented to the user:

blu2

Now whenever the activity finishes, it will return the asking code we take sent (REQUEST_BLU), along with the data and a result lawmaking to our main activity through the onActivityResult callback method.  We know which request code we have to cheque against, merely how about theresult lawmaking?  Elementary: if the user responds "No" to the above permission asking (or if an mistake occurs), the result lawmaking volition be RESULT_CANCELED. On the other hand, if the user accepts,  the BT documentation specifies that the issue code will be equal to the duration that the device is discoverable (i.eastward. DISCOVER_DURATION, i.east. 300).

So the fashion to process the BT dialog above would exist:

// When startActivityForResult completes... protected void onActivityResult (int requestCode,                                  int resultCode,                                  Intent data) {    if (resultCode == DISCOVER_DURATION        && requestCode == REQUEST_BLU) {        // processing code goes here   }   else{ // cancelled or error     Toast.makeText(this, R.string.blu_cancelled,                    Toast.LENGTH_SHORT).show();   }  }  Putting all our processing flow in order, here's what nosotros are basically doing:

bt-processflow

Are we done yet? Well-nigh. Last but not least, nosotros demand to enquire for the BT permissions in the Android manifest:

<uses-permission android:proper noun="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

We're ready to deploy at present. To test all this, we demand to use at least ii Android devices, one beingness the file sender (where our application is installed) and the other any receiving device supporting BT. Here are the screen shots. For the sender:

send-shots1

And the corresponding receiving device :

recv-shots2
Note that, once the receiver accepts the connection. the received file (kmemo.dat) is saved inside the BT folder on the SD card. All the lower-level data transfer has been handled by the Android Os.

leetherfull43.blogspot.com

Source: https://www.javacodegeeks.com/2013/09/bluetooth-data-transfer-with-android.html

0 Response to "Share Images With Bluetooth Programmatically Android What Activity to Launch"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel