Printing Using USB cable issue - java

I am using following code to print through android device with USB cable attached to my Samsung printer.
When use startPrinting method it give me following verification in debugging log:
Command to printer sent successfully
Permission from printer granted.
and the printer even starts beeping, but the data I provide does not get printed. I am stuck at this stage and have found no help from google or on stackoverflow either.
Note: There is no crash no error either
I am testing this code on Android Jelly bean 4.3 OS
Any help would be appreciated.
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbInterface mInterface;
private UsbEndpoint mEndPoint;
private PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static Boolean forceCLaim = true;
HashMap<String, UsbDevice> mDeviceList;
Iterator<UsbDevice> mDeviceIterator;
int protocol;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mDeviceList = mUsbManager.getDeviceList();
mDeviceIterator = mDeviceList.values().iterator();
Button print = (Button) findViewById(R.id.buttonPrint);
Toast.makeText(this, "Device List Size: " + String.valueOf(mDeviceList.size()), Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.usbDevice);
String usbDevice = "";
// This is just testing what devices are connected
while (mDeviceIterator.hasNext())
{
UsbDevice usbDevice1 = mDeviceIterator.next();
usbDevice += "\n" + "DeviceID: " + usbDevice1.getDeviceId() + "\n" + "DeviceName: " + usbDevice1.getDeviceName() + "\n" + "DeviceClass: " + usbDevice1.getDeviceClass() + " - "
+ translateDeviceClass(usbDevice1.getDeviceClass()) + "\n" + "DeviceSubClass: " + usbDevice1.getDeviceSubclass() + "\n" + "VendorID: " + usbDevice1.getVendorId() + "\n" + "ProductID: " + usbDevice1.getProductId()
+ "\n";
protocol = usbDevice1.getDeviceProtocol();
int interfaceCount = usbDevice1.getInterfaceCount();
Toast.makeText(this, "INTERFACE COUNT: " + String.valueOf(interfaceCount), Toast.LENGTH_SHORT).show();
mDevice = usbDevice1;
if (mDevice == null)
{
Toast.makeText(this, "mDevice is null", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(this, "mDevice is not null", Toast.LENGTH_SHORT).show();
}
textView.setText(usbDevice);
}
if (mDevice == null)
{
Toast.makeText(this, "mDevice is null", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(this, "mDevice is not null", Toast.LENGTH_SHORT).show();
}
print.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (mDevice != null)
mUsbManager.requestPermission(mDevice, mPermissionIntent);
// else
// Toast.makeText(this, "USB ", Toast.LENGTH_SHORT).show();
// print(mConnection, mInterface);
}
});
}
private String translateDeviceClass(int deviceClass)
{
switch (deviceClass)
{
case UsbConstants.USB_CLASS_APP_SPEC:
return "Application specific USB class";
case UsbConstants.USB_CLASS_AUDIO:
return "USB class for audio devices";
case UsbConstants.USB_CLASS_CDC_DATA:
return "USB class for CDC devices (communications device class)";
case UsbConstants.USB_CLASS_COMM:
return "USB class for communication devices";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "USB class for content security devices";
case UsbConstants.USB_CLASS_CSCID:
return "USB class for content smart card devices";
case UsbConstants.USB_CLASS_HID:
return "USB class for human interface devices (for example, mice and keyboards)";
case UsbConstants.USB_CLASS_HUB:
return "USB class for USB hubs";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "USB class for mass storage devices";
case UsbConstants.USB_CLASS_MISC:
return "USB class for wireless miscellaneous devices";
case UsbConstants.USB_CLASS_PER_INTERFACE:
return "USB class indicating that the class is determined on a per-interface basis";
case UsbConstants.USB_CLASS_PHYSICA:
return "USB class for physical devices";
case UsbConstants.USB_CLASS_PRINTER:
return "USB class for printers";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "USB class for still image devices (digital cameras)";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return "Vendor specific USB class";
case UsbConstants.USB_CLASS_VIDEO:
return "USB class for video devices";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "USB class for wireless controller devices";
default:
return "Unknown USB class!";
}
}
// Broadcast receiver to obtain permission from user for connection
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (device != null)
{
// call method to set up device communication
mInterface = device.getInterface(0);
mEndPoint = mInterface.getEndpoint(0);
mConnection = mUsbManager.openDevice(device);
Log.i("Info", "Device permission granted");
startPrinting(device);
// setup();
}
}
else
{
// Log.d("SUB", "permission denied for device " + device);
Toast.makeText(context, "PERMISSION DENIED FOR THIS DEVICE", Toast.LENGTH_SHORT).show();
}
}
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
Handler handler = new Handler();
handler.post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
// usbInterface = printerDevice.getInterface(0);
for (int i = 0; i < printerDevice.getInterfaceCount(); i++)
{
usbInterface = printerDevice.getInterface(i);
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER)
{
// usbInterface = mDevice;
}
}
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = mUsbManager.openDevice(mDevice);
conn.claimInterface(usbInterface, true);
String myStringData = "TEXT";
myStringData += "\n";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint, myStringData.getBytes(), myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " + transfered);
}
catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
}
finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception", "Unable to release resources because : " + e.getMessage());
e.printStackTrace();
}
}
}
});
}
private void print(UsbDeviceConnection connection, UsbInterface intrface)
{
String test = "THIS IS A PRINT TEST";
// String text = "#move " + protocol + ";" + "#print" + test;
// Log.e("text", text);
byte[] testBytes = test.getBytes();
if (intrface == null)
{
Toast.makeText(this, "INTERFACE IS NULL", Toast.LENGTH_SHORT).show();
}
if (connection == null)
{
Toast.makeText(this, "CONNECTION IS NULL", Toast.LENGTH_SHORT).show();
}
if (forceCLaim == null)
{
Toast.makeText(this, "FORCE CLAIM IS NULL", Toast.LENGTH_SHORT).show();
}
connection.claimInterface(intrface, forceCLaim);
connection.bulkTransfer(mEndPoint, testBytes, testBytes.length, 0);
connection.close();
}

I have had this exact behavior from other operating systems, when the printer manufacturer uses a proprietary (and non disclosed :-( ) protocol over the USB bus. Specifically, the HP Laserjet P1060 series comes to mind. Both with GNU/Linux and Mac OS-X, the OS discoveres the printer quite well, and tries to print using a generic driver (e.g. HP Laserjet II). The printer's LED starts flashing - but nothing comes out. This felt a little as if some command was missing to make the printer actually print the page.
In these cases, a proprietary firmware blob needed to be downloaded to make things work. Unfortunately, it may be difficult to find such a driver for Android for home/small business printer models. I have had some luck with the Samsung Mobile Print Application (http://www.samsung.com/us/mobile-print-app/) with departamental networked laser printers (ML 3471-ND and suchlike). This was over Wifi + Ethernet.
HTH.

From your description everything seems to work - data transfer is happening, there are no errors but printing is not producing anything. Possibly because the Samsung printer is a page printer and the code you have is good for line-printing (Pos printers and Dot Matrix). In such a case the data will reside in the print buffer waiting for the page to be completed. Try to force a page to complete by issuing a formfeed and check.

Related

Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices

I am building an Android app that advertises small packets of information as well as scan for information using BLE.
The code for advertising is:
AdvertiseSettings advSettings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
.setConnectable(false)
.build();
AdvertiseData advData = new AdvertiseData.Builder()
.setIncludeTxPowerLevel(true)
.addServiceUuid(uuid)
.build();
AdvertiseData advScanResponse = new AdvertiseData.Builder()
.setIncludeDeviceName(false)
.addServiceData(uuid,"1234567890".getBytes( Charset.forName( "UTF-8" ) ))
.build();
AdvertiseCallback advCallback = new AdvertiseCallback() {
String TAG="status";
#Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e(TAG, "Not broadcasting: " + errorCode);
int statusText;
switch (errorCode) {
case ADVERTISE_FAILED_ALREADY_STARTED:
Log.w(TAG, "ADVERTISE_FAILED_ALREADY_STARTED");
break;
case ADVERTISE_FAILED_DATA_TOO_LARGE:
Log.w(TAG, "ADVERTISE_FAILED_DATA_TOO_LARGE");
break;
case ADVERTISE_FAILED_FEATURE_UNSUPPORTED:
Log.w(TAG, "ADVERTISE_FAILED_FEATURE_UNSUPPORTED");
break;
case ADVERTISE_FAILED_INTERNAL_ERROR:
Log.w(TAG, "ADVERTISE_FAILED_INTERNAL_ERROR");
break;
case ADVERTISE_FAILED_TOO_MANY_ADVERTISERS:
Log.w(TAG, "ADVERTISE_FAILED_TOO_MANY_ADVERTISERS");
break;
default:
Log.wtf(TAG, "Unhandled error: " + errorCode);
}
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Log.v(TAG, "Advertising started");
mText.setText(uuid.toString());
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
};
mBluetoothAdapter.getBluetoothLeAdvertiser()
.startAdvertising(advSettings, advData, advScanResponse, advCallback);
and the code for listening is as follows:
mBluetoothLeScanner=mBluetoothAdapter.getBluetoothLeScanner();
ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
if( result == null
|| result.getDevice() == null
)
return;
if(result.getScanRecord().getServiceUuids()!=null) {
ParcelUuid pp=result.getScanRecord().getServiceUuids().get(0);
StringBuilder builder = new StringBuilder((pp.toString()+"\n"));
builder.append(new String (result.getScanRecord().getServiceUuids().size()+""));
mText.setText(builder.toString());
}
I have tested it on multiple phones and it works fine. However, Android version 9.0 on Galaxy S8+ can't scan unless the location is turned on. I also tried in on Android version 9.0 on Redmi Note 7 and it works perfectly without the need of turning on the location. What is causing my problem?
Not sure about the Android settings on the Redmi Note 7, but for Android 9 devices ACCESS_COARSE_LOCATION needs to be turned on in order for Bluetooth to function. Maybe this is somehow turned on on the Redmi Note 7 regardless of the location settings, whereas on the S8+ this is tied to the location settings.
You can find more information here:-
https://stackoverflow.com/a/58232014/2215147
I hope this helps.

Android In-App Billing: Ads are not removing when In-App is made

I have implemented In-App Billing in my Activity
this is my onIabPurchaseFinished() method:
#Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (!verifyDeveloperPayload(info)) {
Toast.makeText(this, R.string.error_purchasing, Toast.LENGTH_LONG).show();
}
Toast.makeText(this, R.string.premium_bought, Toast.LENGTH_LONG).show();
if (info.getSku().equals("chords_premium")) {
/** salva isPremium tra SharedPreferences */
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("status", "purchased");
editor.apply();
}
}
As you can see I save the String "status" to SharedPreferences so that I can access it from anywhere, and keep it stored even after the app is closed.
Then in my other Activities where ads are implemented I wrote like this:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final String status = prefs.getString("status", "free");
/** gestisce le pubblicita */
if (status.equals("free")) {
MobileAds.initialize(getApplicationContext(), "ca-app-pub-6723047396589178/2654753246");
AdView listBanner = (AdView) findViewById(R.id.chords_list_banner);
AdRequest adRequest = new AdRequest.Builder().build();
listBanner.loadAd(adRequest);
/** carica Ad a tutto schermo */
chordsListAd = new InterstitialAd(this);
chordsListAd.setAdUnitId("ca-app-pub-6723047396589178/7447672046");
requestNewInterstitial();
chordsListAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
}
As you can see here the Ads are surrounded by an if statement that checks if the "status"String is set to free.
The problem is that when I buy Premium, the Ads are still shown. How can I fix it?
It's because you are saving your data in Base Context and trying to find it in the current Activity context using (this).
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
to
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Also, a more recommeded way to query In-App purchased items is to query In- App inventory instead of storing in sharedprefs.
As mention in Google Docs
Query Purchased Items
Upon a successful purchase, the user’s purchase data is cached locally by Google Play’s In-app Billing service. It is good practice to frequently query the In-app Billing service for the user’s purchases, for example whenever the app starts up or resumes, so that the user’s current in-app product ownership information is always reflected in your app.
To retrieve the user’s purchases from your app, call queryInventoryAsync(QueryInventoryFinishedListener) on your IabHelper instance. The QueryInventoryFinishedListener argument specifies a listener that is notified when the query operation has completed and handles the query response. It is safe to make this call fom your main thread.
mHelper.queryInventoryAsync(mGotInventoryListener); //mHelper is IabHelper instance
If the query is successful, the query results are stored in an Inventory object that is passed back to the listener. The In-app Billing service returns only the purchases made by the user account that is currently logged in to the device.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else {
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
// update UI accordingly
}
}
};
Check if the inapp purchase is made:
//*************************************checking in app purchase has been made********************************//
void testInApp()
{
if (!blnBind) return;
if (mService == null) return;
int result;
try {
result = mService.isBillingSupported(3, getPackageName(), "inapp");
//Toast.makeText(context, "isBillingSupported() - success : return " + String.valueOf(result), Toast.LENGTH_SHORT).show();
Log.i(tag, "isBillingSupported() - success : return " + String.valueOf(result));
} catch (RemoteException e) {
e.printStackTrace();
//Toast.makeText(context, "isBillingSupported() - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "isBillingSupported() - fail!");
return;
}
}
void checkInApp()
{
if (!blnBind) return;
if (mService == null) return;
Bundle ownedItems;
try {
ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
//Toast.makeText(context, "getPurchases() - success return Bundle", Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - success return Bundle");
} catch (RemoteException e) {
e.printStackTrace();
//Toast.makeText(context, "getPurchases - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "getPurchases() - fail!");
return;
}
int response = ownedItems.getInt("RESPONSE_CODE");
//Toast.makeText(context, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response), Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response));
if (response != 0) return;
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_ITEM_LIST\" return " + ownedSkus.toString());
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_DATA_LIST\" return " + purchaseDataList.toString());
Log.i(tag, "getPurchases() - \"INAPP_DATA_SIGNATURE\" return " + (signatureList != null ? signatureList.toString() : "null"));
Log.i(tag, "getPurchases() - \"INAPP_CONTINUATION_TOKEN\" return " + (continuationToken != null ? continuationToken : "null"));
// TODO: management owned purchase
try {
if(purchaseDataList.size()>0){
jinapp=new JSONArray(purchaseDataList.toString());
JSONObject c = jinapp.getJSONObject(0);
String productid=c.getString("productId");
if(productid!=null){
SharedPreferences.Editor editor = prefpurchase.edit();
editor.putBoolean(Constants.APP_IS_PURCHASED,true);
editor.commit();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO: management owned purchase
}
Write the code in your SplashScreen
Now in the activity/fragment in which you are showing your ad,write the following code:
//*******************to check purchase has been made.If yes disable ads and no then show ads******************//
prefpurchase = this.getSharedPreferences(Constants.GET_IN_APP_STATE, Context.MODE_PRIVATE);
//Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();
//In App Purchase
ispurchased=prefpurchase.getBoolean(Constants.APP_IS_PURCHASED,false);
System.out.println("ispurchased-->"+ispurchased);
if(ispurchased)
{
setContentView(R.layout.activity_home_noads);
}else{
System.out.println("Getting ad");
setContentView(R.layout.activity_home);
//Locate the Banner Ad in activity_main.xml
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
// Add a test device to show Test Ads
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
//.addTestDevice("B2D63***************************")
.build();
// Load ads into Banner Ads
adView.loadAd(adRequest);
}
//*******************************************************************************************************//
The logic is simple,you are creating two versions of your layout,one with ad and the other without ad.
Load the correct layout depending on the value of sharedpreference.
mService:
Write this code globally in splashscreen before onCreate():
private IInAppBillingService mService;
private ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
blnBind
Declare blnBind globally:
boolean blnBind;
In onCreate() of SplashActivity write:
// Bind Service
blnBind = bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
//Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();
Log.i(tag, "bindService - return " + String.valueOf(blnBind));
//In App Purchase
GET_IN_APP_STATE or APP_IS_PURCHASED are created for shared Preferences,that acts as a key for preference values.
//Preferences to check in app purchase
final static public String GET_IN_APP_STATE = "prefinapp";
public static final String APP_IS_PURCHASED ="AppIsPurchased";
Whenever a purchase is made,don't forget to set the shared preference value to true.

How to launch specific activity from GooglePlayGames invitation

I'm trying to create a new android application that is comprised of multiple mini-games. The launcher activity extends BaseGameActivity and has a sign-in button and a ListView containing all the possible games that can be played.
Inside of a mini-game activity (also extends BaseGameActivity), how can I get it to create a notification which will launch a specific Activity? Currently, when I call invitePlayersToGame, the invitation that gets sent is for the full application (Mini-Games) and not the individual game (specific dice game).
public void invitePlayersToGame(View pView) {
Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(getApiClient(), 1, 1);
intent.putExtra("gameName", "Patman Yahtzee");
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
Is there a way to get the notification to generate with a specific message? Is there a way to get notification to open directly to the mini-game activity without going to the main launcher activity first?
Any help is appreciated. Thanks!
You can send sendReliableMessage for method handshaking.
First enter a room (quickgame or send invite).
public void openInvitationIntent() {
// launch the player selection screen
// minimum: 1 other player; maximum: 1 other players
Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(mGoogleApiClient, 1, 1);
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
onConnected:
#Override
public void onConnected(Bundle connectionHint) {
// QuickGame
if (mGameMode == 1) {
Log.d(TAG, "onConnected() called. Sign in successful!");
Log.d(TAG, "Sign-in succeeded.");
startQuickGame();
// register listener so we are notified if we receive an invitation to play
// while we are in the game
if (connectionHint != null) {
Log.d(TAG, "onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
Log.d(TAG, "onConnected: connection hint has a room invite!");
acceptInviteToRoom(inv.getInvitationId());
return;
}
}
}
// Send request
else if (mGameMode == 0) {
// request code for the "select players" UI
// can be any number as long as it's unique
invitationInbox();
}
// request accepted
else {
mIncomingInvitationId = getIntent().getExtras().getString(AppConstants.RC_INVITATION_ID);
RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
roomConfigBuilder.setInvitationIdToAccept(mIncomingInvitationId);
Games.RealTimeMultiplayer.join(mGoogleApiClient, roomConfigBuilder.build());
// prevent screen from sleeping during handshake
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
After this, you can send model class (includes what you need).
private void broadcastMessage(ModelGameRecievedMessage broadcastedMessage, boolean isFinal) {
try {
if ( mParticipants != null && broadcastedMessage != null) {
byte[] bytes = Utils.serialize(broadcastedMessage);
// Send to every other participant.
for (Participant p : mParticipants) {
if (p.getParticipantId().equals(mMyId)) {
continue;
}
if (p.getStatus() != Participant.STATUS_JOINED) {
continue;
}
if (mRoomId != null) {
if (isFinal) {
// final score notification must be sent via reliable broadcastedMessage
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient, null, bytes,
mRoomId, p.getParticipantId());
} else {
// it's an interim score notification, so we can use unreliable
Games.RealTimeMultiplayer.sendUnreliableMessage(mGoogleApiClient, bytes,
mRoomId, p.getParticipantId());
}
}
}
Logy.l("broadcastedMessage.getMessageTypeId(); " + broadcastedMessage.getMessageTypeId());
Logy.l("broadcastedMessage.getMessage(); " + broadcastedMessage.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
}
finally you can reach the data on other devices:
#Override
public void onRealTimeMessageReceived(RealTimeMessage rtm) {
byte[] bufy = rtm.getMessageData();
ModelGameRecievedMessage recievedMessage = null;
try {
recievedMessage = (ModelGameRecievedMessage) Utils.deserialize(bufy);
Logy.l("recievedMessage.getMessageTypeId(); " + recievedMessage.getMessageTypeId());
Logy.l("recievedMessage.getMessage(); " + recievedMessage.getMessage());
} catch (Exception e) {
Logy.e("Exception onRealTimeMessageReceived deserialize: " + e);
}
switch (recievedMessage.getMessageTypeId()) {
case AppConstants.RC_MULTI_START_TIMEMILIS_MULTIPLAYER:
....

Bluetooth LE Gatt connection Android 4.4 to read real-time RSSI

I am trying to write a small android app (4.4) which searches for several Bluetooth LE devices. Once it has found each device it needs to connect to it and then continually read the RSSI of each device as quickly as it can. I have been trying to get this to work with 6 devices. My current code is as follows:
public class BluetoothGatt extends Activity {
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
System.out.println("Adapter: " + mBluetoothAdapter);
BTScanStart();
}
// Start the Bluetooth Scan
private void BTScanStart() {
if (mBluetoothAdapter == null) {
System.out.println("Bluetooth NOT supported. Aborting.");
return;
} else {
if (mBluetoothAdapter.isEnabled()) {
System.out.println("Bluetooth is enabled...");
// Starting the device discovery
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
count++;
System.out.println("Found " + count + ":" + device + " " + rssi + "db");
device.connectGatt(null, false, mGattCallback);
if (count > 5) mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
};
// Gatt Callback
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
System.out.println(gatt.getDevice() + ": Connected.. ");
gatt.readRemoteRssi();
}
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
System.out.println(gatt.getDevice() + ": Disconnected.. ");
}
}
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
System.out.println(gatt.getDevice() + " RSSI:" + rssi + "db ");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.readRemoteRssi();
}
};
}
I am having the following problems:
1) It connects to the devices successfully, but they all disconnect after around 5 seconds with a 'btm_sec_disconnected - Clearing Pending flag' error. Is there a was to keep them connected?
2) The code works fine for a single device, however when using more than one device only one device prints RSSI updates regularly, others update randomly and some don't update at all.
3) I am not sure what context I should supply when calling device.connectGatt .
Thank you in advance for your thoughts!
For the RSSI issue I will second Sam's answer (https://stackoverflow.com/a/20676785/4248895). It seems that for your use case continuously scanning should be sufficient. You don't want to add the overhead of connection if you can avoid it.
I will answer your other question in that if you do need to connect to these devices for some reason, your stability issues may be related to the fact that you're connecting and scanning simultaneously. Generally speaking, you should not perform any two gatt operations (scanning, connecting, reading, writing, etc.) at the same time.
How about just use startLeScan and get rssi?
If your android device filter the ble devices (like nexus 7), you could stopLeScan/ startLeScan repeatedly.
If not(like samsung s4 with android 4.3), just let it scan, onLeScan(...) will give every devices' rssi continuously.

Android returning "null" for Bluetooth RSSI

I am developing a android application using Eclipse to return the RSSI values of a Bluetooth device. I have modified the Android Bluetooth Chat example to fit my needs, but I am having problems returning the RSSI value. After hitting the scan button to discover nearby devices it returns the device name, device address, and is also suppose to return the RSSI value but instead it says null for the RSSI.
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress() + getRssi());
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Get the Bluetooth RSSI
short Rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// If it's already paired, skip it, because it's been listed already
// Added getRssi()
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress() + getRssi());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
I haven't tried it myself, but maybe this SO answer will help:
https://stackoverflow.com/a/2361630/831918
Supposedly it is possible using the NDK. Good luck!
This is how I am getting RSSI
String deviceRSSI =
(intent.getExtras()).get(BluetoothDevice.EXTRA_RSSI).toString();
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceRSSI = (intent.getExtras()).get(BluetoothDevice.EXTRA_RSSI).toString();
btArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + deviceRSSI);
btArrayAdapter.notifyDataSetChanged();
}
if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
}
}
};

Categories

Resources