I am realizing pdf viewer function using APV library
when I load pdf file using APV library I mentioned, some part of pages are invisible and sometimes not.
Invisible parts are sometimes paragraph and sometimes picture etc. I think it does not depend on object but trial.
Does anyone have similar problem? If anyone knows, please let me know.
I attached 2 picture that have same page, one normal and the other abnormal.
abnormal
normal
public class mPDFActivity extends PdfViewerActivity {
byte[] startSign = {0x31};
byte[] stopSign = {0x32};
public static boolean isPDFPageRunning = false; // bluetoothservice에서 이 activity로 신호 보낼 때 해당 변수 상태 보고 동작(page 넘김) 할지 말지 결정
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
public int getMenuOpenFile() {return R.drawable.openfile;}
public int getMenuScanBluetooth() {return R.drawable.ic_action_device_access_bluetooth_searching;}
public Handler PDFHandler;
mPDFActivity currentActivity;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig .orientation == newConfig.ORIENTATION_LANDSCAPE)
{
}else{
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
isPDFPageRunning = true;
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
//FragmentActivity activity = getActivity();
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_LONG).show();
this.finish();
}
byte a[] = {(byte)0x01, (byte)0xff};
if(a[1] == -1) {
int re = Conversion.ByteArraytoInteger(a[0], a[1]);
}
Log.d(TAG,"KK");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pref = getSharedPreferences("PDF",0);
SharedPreferences.Editor edit = pref.edit();
if(isAlreadyCreated)
{
}else{
}
edit.putFloat(Constants.ZOOM, mZoom);
edit.putInt(Constants.PAGE, mPage);
edit.commit();
}
#Override
protected void onResume() {
isPDFPageRunning = true;
super.onResume();
float zoom;
int page;
SharedPreferences pref = getSharedPreferences(Constants.PDF, 0);
zoom = pref.getFloat(Constants.ZOOM,1);
page = pref.getInt(Constants.PAGE,1);
if(!isAlreadyCreated){
}
}
#Override
protected void onStop() {
isPDFPageRunning = false;
super.onStop();
}
#Override
protected void onDestroy() {
isPDFPageRunning = false;
super.onDestroy();
mChatService.write(stopSign);
if (mChatService != null) {
mChatService.stop();
}
}
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
//public BluetoothChatService mChatService = null;
public BluetoothChatService mChatService = null;
ArrayAdapter adapter;
int clickCounter=0;
ArrayList listItems=new ArrayList();
private File[] imagelist;
String[] pdflist;
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
private void setupChat() {
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
//setupChat();
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
this.finish();
}
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//Activity activity = getApplicationContext();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(getString(R.string.title_connecting));
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(getString(R.string.title_not_connected));
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
break;
case Constants.MESSAGE_READ:
/*
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.what);
//Log.i(TAG,readMessage);
//mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
int bytes = msg.arg1; // length of read bytes array
String str = Conversion.byteArraytoHexString(readBuf).substring(0, bytes * 2);
str = str.substring(str.indexOf("ff"));
while(str.length() >= 10)
{
String datA = str.substring(2,5);
String datB = str.substring(6,9);
int dat1 = Conversion.hexStringtoInteger(datA);
int dat2 = Conversion.hexStringtoInteger(datB);
//TODO: 데이터 저장 및 신호처리
str = str.substring(10);
}
Log.e("READ","READ : " + str);
*/
//TODO : mPDFActivity로 메시지에 따른 intent 날려
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
mChatService.write(startSign);
}
break;
case Constants.MESSAGE_TOAST:
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_PREV_PAGE:
prevPage();
break;
case Constants.MESSAGE_NEXT_PAGE:
nextPage();
break;
case Constants.MESSAGE_VIBRATE:
Vibrator vb = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
int duration = msg.getData().getInt(Constants.VIBRATE);
vb.vibrate(duration);
break;
}
}
};
/**
* Establish connection with other divice
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
Activity activity = this;
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
}
Related
I'm new in android develop and I'm developing an app that transmit/receive data to a BLE module via Uart service.
With smartphone android 5.x.x the app works fine, it connects with the hardware and receive/transmit data.
With smartphone android 7.x.x the app doesn't connects.
Below you can see a snippet of MainActivity.java:
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "HW_CONNECT_MSG");
DisconnectButton.setEnabled(true);
DeviceInfo.setText("Device Information:");
DeviceName.setText(mDevice.getName() + " - Connected");
mState = UART_PROFILE_CONNECTED;
isConnected = true;
if(isConnected) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x43; // 'C';
Connectcmd[3] = (byte) 0x54; // 'T'
Connectcmd[4] = (byte) ETX;
try {
//send data to UART service
SendData(Connectcmd);
sleep(500); // wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
else
{
isConnected = false;
}
}
});
}
It's seem that when SendData, the GATT operation is not yet finished. Smartphone show the message "Device doesn't support UART over BLE. Disconnecting..." due to action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART).
If I delete the if(isConnected)...else... statement also smartphone with android 7.x.x will connects.
My question is what's happen and how can I resolve this issue?
My goal is to send a command to hardware via BLE so when the mcu is connected, a buzzer make a sound.
Thanks for help….
EDIT
Below you can find the whole MainActivity:
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
public static final String TAG = "DEBUG ";
public static final String DEV_NAME_FILTER = "";
private static final int REQUEST_SELECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final int UART_PROFILE_READY = 10;
private static final int UART_PROFILE_CONNECTED = 20;
public static final int UART_PROFILE_DISCONNECTED = 21;
private static final int STATE_OFF = 10;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
TextView mRemoteRssiVal;
RadioGroup mRg;
private int mState = UART_PROFILE_DISCONNECTED;
private static UartService mService = null;
private static BluetoothDevice mDevice = null;
private BluetoothAdapter mBtAdapter = null;
private ListView messageListView;
private ArrayAdapter<String> listAdapter;
private Button SelectButton, DisconnectButton;
private EditText edtMessage;
private static Context context;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private static TextView DeviceInfo;
private static TextView DeviceName;
private static TextView Manufacturer;
public static boolean isConnected;
public static boolean isSetting;
public static boolean isReading;
public static boolean isManual;
public static boolean isFunctional;
public static boolean isBootloader;
public static byte[] SettingValues;
public static byte[] ReadingValues;
public static byte[] ManualValues;
public static byte[] FunctionalValues;
private static byte[] Connectcmd = new byte[5];
public static int STX = 0x3E; // '>'
public static int ETX = 0x23; // '#'
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DeviceInfo = (TextView) findViewById(R.id.deviceInfo);
DeviceName = (TextView) findViewById(R.id.deviceName);
Manufacturer= (TextView) findViewById(R.id.manufacturer);
isConnected = false;
isSetting = false;
isReading = false;
isManual = false;
isFunctional = false;
isBootloader = false;
context = this;
//Enable location
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect beacons.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
SelectButton = (Button) findViewById(R.id.button);
DisconnectButton = (Button) findViewById(R.id.disconnect);
DisconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x44; // 'D';
Connectcmd[3] = (byte) 0x43; // 'C'
Connectcmd[4] = (byte) ETX;
try {
//send data to Banner service
SendData(Connectcmd);
sleep(500); // Wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MainActivity.disconnected();
setContentView(R.layout.activity_main);
finish();
} catch (Exception e) {
Log.e(TAG, "Disconnect error");
}
}
});
// Handle Select device button
SelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onClick - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (SelectButton.getText().equals("SELECT CELU")) {
//Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
Log.i(TAG, "Push button CONNECT");
Intent newIntent = new Intent(context, DeviceListActivity.class);
((Activity) context).startActivityForResult(newIntent, MainActivity.REQUEST_SELECT_DEVICE);
} else {
//Disconnect button pressed
disconnected();
}
}
}
});
// Set initial UI state
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
//UART service connected/disconnected
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((UartService.LocalBinder) rawBinder).getService();
Log.d(TAG, "onServiceConnected mService= " + mService);
if (!mService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
//// mService.disconnect(mDevice);
mService = null;
}
};
private Handler mHandler = new Handler() {
#Override
//Handler events that received from UART service
public void handleMessage(Message msg) {
}
};
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
Log.d(TAG, "CELU_CONNECT_MSG");
//btnConnectDisconnect.setText("Disconnect");
//edtMessage.setEnabled(true);
DisconnectButton.setEnabled(true);
DeviceInfo.setText("Device Information:");
DeviceName.setText(mDevice.getName() + " - Connected");
mState = UART_PROFILE_CONNECTED;
isConnected = true;
//IF COMMENTED THE APP CONNECTS!!!!!!!!!!!!!!!!!!
//ELSE IF NOT COMMENTED THE APP NEVER CONNECTS
/*if(isConnected) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x43; // 'C';
Connectcmd[3] = (byte) 0x54; // 'T'
Connectcmd[4] = (byte) ETX;
try {
//send data to UART service
SendData(Connectcmd);
sleep(500); // Wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
else
{
isConnected = false;
}*/
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
});
}
//*********************//
if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "HW_DISCONNECT_MSG");
DisconnectButton.setEnabled(false);
DeviceName.setText("Not Connected");
mState = UART_PROFILE_DISCONNECTED;
mService.close();
//setUiState();
}
});
}
//Enable notifivcation on UART service//
if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
//*********************//
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
try {
ParsingPacket(txValue);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
//*********************//
if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART)) {
showMessage("Device doesn't support UART over BLE Celu . Disconnecting");
mService.disconnect();
}
}
};
private static void ParsingPacket(byte[] packet) throws Exception {
if (packet.length == 0) {
// received empty packet
isConnected = false;
isSetting = false;
isReading = false;
isManual = false;
isFunctional = false;
isBootloader = false;
}
if(isSetting){
isSetting = false;
SettingValues = packet.clone();
String text = new String(SettingValues, "UTF-8");
Log.d(TAG, text);
}
if(isReading){
ReadingValues= packet;
ReadActivity.updateMeasure(ReadingValues);
//ReadActivity.addData(packet);
//String text = new String(ReadingValues, "UTF-8");
Log.d("Length ", String.format("%02d", (int) ReadingValues.length));
for(int i=0; i<ReadingValues.length; i++) {
String text = String.format("%02x", (int) ReadingValues[i]);
Log.d(TAG, text);
}
}
if(isManual){
isManual = false;
ManualValues = packet.clone();
String text = new String(ManualValues, "UTF-8");
Log.d(TAG, text);
}
if(isFunctional){
isFunctional = false;
FunctionalValues = packet.clone();
String text = new String(FunctionalValues, "UTF-8");
Log.d(TAG, text);
}
if(isBootloader){
isBootloader = false;
// do samething
}
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if(DeviceName.getText()!="Not Connected") {
Intent connectedIntent = new Intent(getApplicationContext(), MenuActivity.class); //new Intent("com.antertech.mybleapplication.MenuActivity");
startActivity(connectedIntent);
}
}
};
private void service_init() {
Intent bindIntent = new Intent(this, UartService.class);
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART);
return intentFilter;
}
#Override
public void onStart() {
super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
Log.e(TAG, ignore.toString());
}
unbindService(mServiceConnection);
mService.stopSelf();
mService = null;
}
#Override
protected void onStop() {
Log.d(TAG, "onStop");
super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
#Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onResume - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_DEVICE:
//When the DeviceListActivity return, with the selected device address
if (resultCode == Activity.RESULT_OK && data != null) {
String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + " mserviceValue " + mService);
mService.connect(deviceAddress);
//setContentView(R.layout.activity_setting);
((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - Connecting...");
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
Log.e(TAG, "wrong request code");
break;
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
public static void SendData(byte[] text) {
mService.writeRXCharacteristic(text);
Log.i(TAG, "Message send to Target");
}
public static void disconnected() {
if (mDevice != null) {
mService.disconnect();
Log.i(TAG, "Push Button DISCONNECT");
}
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
if (mState == UART_PROFILE_CONNECTED) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
showMessage("CELU TPE running in background.\n Disconnect to exit");
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.popup_title)
.setMessage(R.string.popup_message)
.setPositiveButton(R.string.popup_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.popup_no, null)
.show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[],
int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
I am using magtek card reader audio uDynamo device and i am integrating sdk with my android application. But when i am trying to open device through openDevice() method. Application unfortunately stopped. Why its doing like this ?
This is what i am doing
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
// here its stopping
m_SCRA.openDevice();
Full source code
public class MainActivity extends AppCompatActivity {
private MTSCRA m_SCRA;
private Button btn;
private TextView txt;
private TextView txt1;
private TextView msg;
private TextView msg2;
private boolean m_startTransactionActionPending;
private boolean m_turnOffLEDPending;
private EditText Edit;
private AudioManager m_audioManager;
private int m_audioVolume;
private String m_deviceAddress;
private MTConnectionType m_connectionType;
private MTConnectionState m_connectionState = MTConnectionState.Disconnected;
private Handler m_scraHandler = new Handler(new SCRAHandlerCallback());
private class SCRAHandlerCallback implements Handler.Callback {
public boolean handleMessage(Message msg)
{
try
{
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert Switch");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (msg.what)
{
case MTSCRAEvent.OnDeviceConnectionStateChanged:
OnDeviceStateChanged((MTConnectionState) msg.obj);
break;
case MTSCRAEvent.OnCardDataStateChanged:
OnCardDataStateChanged((MTCardDataState) msg.obj);
break;
case MTSCRAEvent.OnDataReceived:
OnCardDataReceived((IMTCardData) msg.obj);
break;
case MTSCRAEvent.OnDeviceResponse:
OnDeviceResponse((String) msg.obj);
break;
case MTEMVEvent.OnTransactionStatus:
OnTransactionStatus((byte[]) msg.obj);
break;
case MTEMVEvent.OnDisplayMessageRequest:
OnDisplayMessageRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnUserSelectionRequest:
OnUserSelectionRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnARQCReceived:
OnARQCReceived((byte[]) msg.obj);
break;
case MTEMVEvent.OnTransactionResult:
OnTransactionResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnEMVCommandResult:
OnEMVCommandResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnDeviceExtendedResponse:
OnDeviceExtendedResponse((String) msg.obj);
break;
}
}
catch (Exception ex)
{
}
return true;
}
}
public void OnCardDataReceived(IMTCardData cardData)
{
txt.setText(m_SCRA.getCardLast4());
}
protected void OnDeviceStateChanged(MTConnectionState deviceState)
{
setState(deviceState);
updateDisplay();
invalidateOptionsMenu();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert ondevice state");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (deviceState)
{
case Disconnected:
if (m_connectionType == MTConnectionType.Audio)
{
restoreVolume();
}
break;
case Connected:
if (m_connectionType == MTConnectionType.Audio)
{
setVolumeToMax();
}
clearMessage();
clearMessage2();
break;
case Error:
sendToDisplay("[Device State Error]");
break;
case Connecting:
break;
case Disconnecting:
break;
}
}
protected void OnCardDataStateChanged(MTCardDataState cardDataState)
{
switch (cardDataState)
{
case DataNotReady:
sendToDisplay("[Card Data Not Ready]");
break;
case DataReady:
sendToDisplay("[Card Data Ready]");
break;
case DataError:
sendToDisplay("[Card Data Error]");
break;
}
}
protected void OnDeviceResponse(String data)
{
sendToDisplay("[Device Response]");
sendToDisplay(data);
if (m_startTransactionActionPending)
{
m_startTransactionActionPending = false;
startTransaction();
}
}
protected void OnTransactionStatus(byte[] data)
{
sendToDisplay("[Transaction Status]");
//sendToDisplay(TLVParser.getHexString(data));
}
protected void OnDisplayMessageRequest(byte[] data)
{
sendToDisplay("[Display Message Request]");
//String message = TLVParser.getTextString(data, 0);
//sendToDisplay(message);
//displayMessage(message);
}
protected void OnEMVCommandResult(byte[] data)
{
sendToDisplay("[EMV Command Result]");
//sendToDisplay(TLVParser.getHexString(data));
if (m_turnOffLEDPending)
{
m_turnOffLEDPending = false;
setLED(false);
}
}
protected void OnDeviceExtendedResponse(String data)
{
sendToDisplay("[Device Extended Response]");
sendToDisplay(data);
}
protected void OnUserSelectionRequest(byte[] data)
{
sendToDisplay("[User Selection Request]");
//sendToDisplay(TLVParser.getHexString(data));
//processSelectionRequest(data);
}
protected void OnARQCReceived(byte[] data)
{
sendToDisplay("[ARQC Received]");
/*sendToDisplay(TLVParser.getHexString(data));
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(data, true, "");
if (parsedTLVList != null)
{
String deviceSNString = TLVParser.getTagValue(parsedTLVList, "DFDF25");
byte[] deviceSN = TLVParser.getByteArrayFromHexString(deviceSNString);
sendToDisplay("SN Bytes=" + deviceSNString);
sendToDisplay("SN String=" + TLVParser.getTextString(deviceSN, 2));
boolean approved = true;
if (mMainMenu != null)
{
approved = mMainMenu.findItem(R.id.menu_emv_approved).isChecked();
}
byte[] response = buildAcquirerResponse(deviceSN, approved);
setAcquirerResponse(response);
}*/
}
protected void OnTransactionResult(byte[] data)
{
sendToDisplay("[Transaction Result]");
//sendToDisplay(TLVParser.getHexString(data));
/*if (data != null)
{
if (data.length > 0)
{
boolean signatureRequired = (data[0] != 0);
int lenBatchData = data.length - 3;
if (lenBatchData > 0)
{
byte[] batchData = new byte[lenBatchData];
System.arraycopy(data, 3, batchData, 0, lenBatchData);
sendToDisplay("(Parsed Batch Data)");
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(batchData, false, "");
displayParsedTLV(parsedTLVList);
String cidString = TLVParser.getTagValue(parsedTLVList, "9F27");
byte[] cidValue = TLVParser.getByteArrayFromHexString(cidString);
boolean approved = false;
if (cidValue != null)
{
if (cidValue.length > 0)
{
if ((cidValue[0] & (byte) 0x40) != 0)
{
approved = true;
}
}
}
if (approved)
{
if (signatureRequired)
{
displayMessage2("( Signature Required )");
}
else
{
displayMessage2("( No Signature Required )");
}
}
}
}
}
setLED(false);*/
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = ( Button) findViewById(R.id.btn);
txt = (TextView) findViewById(R.id.txt1);
txt1 = (TextView) findViewById(R.id.txt2);
msg = (TextView) findViewById(R.id.msgtext1);
msg2 = (TextView) findViewById(R.id.msgtext2);
Edit = (EditText) findViewById(R.id.editText);
//m_SCRA.setConnectionType(MTConnectionType.Audio);
//if (! m_SCRA.isDeviceConnected())
//{
// m_SCRA.openDevice();
//}
m_audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
m_SCRA = new MTSCRA(this, m_scraHandler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
m_connectionType = MTConnectionType.Audio;
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
m_SCRA.openDevice();
}
});
}
private void sendToDisplay(final String data)
{
if (data != null)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Edit.append(data + "\n");
}
});
}
}
private void setState(MTConnectionState deviceState)
{
m_connectionState = deviceState;
updateDisplay();
invalidateOptionsMenu();
}
private void updateDisplay()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (m_connectionState == MTConnectionState.Connected)
{
updateConnectionState(R.string.connected);
}
else if (m_connectionState == MTConnectionState.Connecting)
{
updateConnectionState(R.string.connecting);
}
else if (m_connectionState == MTConnectionState.Disconnecting)
{
updateConnectionState(R.string.disconnecting);
}
else if (m_connectionState == MTConnectionState.Disconnected)
{
updateConnectionState(R.string.disconnected);
}
}
});
}
private void updateConnectionState(final int resourceId)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
txt1.setText(resourceId);
}
});
}
private void restoreVolume()
{
setVolume(m_audioVolume);
}
private void setVolumeToMax()
{
saveVolume();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert volume max");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
int volume = m_audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
setVolume(volume);
}
private void setVolume(int volume)
{
m_audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
}
private void saveVolume()
{
m_audioVolume = m_audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
private void clearMessage()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText("");
}
});
}
private void clearMessage2()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg2.setText("");
}
});
}
public void startTransaction()
{
if (m_SCRA != null)
{
byte timeLimit = 0x3C;
//byte cardType = 0x02; // Chip Only
byte cardType = 0x03; // MSR + Chip
byte option = 0x00;
byte[] amount = new byte[] {0x00, 0x00, 0x00, 0x00, 0x15, 0x00};
byte transactionType = 0x00; // Purchase
byte[] cashBack = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] currencyCode = new byte[] { 0x08, 0x40};
byte reportingOption = 0x02; // All Status Changes
clearMessage();
clearMessage2();
int result = m_SCRA.startTransaction(timeLimit, cardType, option, amount, transactionType, cashBack, currencyCode, reportingOption);
sendToDisplay("[Start Transaction] (Result=" + result + ")");
}
}
public void setLED(boolean on)
{
if (m_SCRA != null)
{
if (on)
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_ON);
}
else
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_OFF);
}
}
} }
I was facing the same issue. It turned out that I forgot audio recording runtime permission.
private void checkRecordPermission() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO},
123);
}
}
I'm writinng Android app that receiving data via bluetooth from another device. Those data as in fact streaming non-stop. After getting about 50 or 70 of them, app slows down and stop showing me received data. App cache is full, but clearing it (deleting context.getCacheDir()) doesn't help. After restarting whole app, I can again get next part of data. WHat can I do for avoiding this "lag"?
my MainActivity:
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private boolean pendingRequestEnableBt = false;
private final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
private BluetoothResponseHandler mHandler;
private static MainActivity instance;
private DeviceConnector connector;
private TextView console;
private String deviceName;
private final int REQUEST_CONNECT_DEVICE = 1;
private final int REQUEST_ENABLE_BT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console = (TextView) findViewById(R.id.main_text_console);
if (savedInstanceState != null) {
pendingRequestEnableBt = savedInstanceState.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "No bluetooth available", Toast.LENGTH_LONG).show();
}
if (mHandler == null) {
mHandler = new BluetoothResponseHandler(this);
} else {
mHandler.setTarget(this);
}
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
getActionBar().setSubtitle(deviceName);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
outState.putString("device_name", deviceName);
if (console != null) {
final String log = console.getText().toString();
outState.putString("AC", log);
}
}
public boolean isAdapterReady() {
return (bluetoothAdapter != null) && (bluetoothAdapter.isEnabled());
}
private static class BluetoothResponseHandler extends Handler {
private WeakReference<MainActivity> mActivity;
public BluetoothResponseHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
public void setTarget(MainActivity target) {
mActivity.clear();
mActivity = new WeakReference<MainActivity>(target);
}
#Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
if (activity != null) {
if (msg.what==MessageType.MESSAGE_STATE_CHANGE.getValue()) {
final ActionBar bar = activity.getActionBar();
switch (msg.arg1) {
case DeviceConnector.STATE_CONNECTED:
bar.setSubtitle("Połączono.");
break;
case DeviceConnector.STATE_CONNECTING:
bar.setSubtitle("Łączenie");
break;
case DeviceConnector.STATE_NONE:
bar.setSubtitle("Rozłączono.");
break;
}
} else if (msg.what==MessageType.MESSAGE_READ.getValue()) {
if (msg.obj != null) {
activity.appendLog((String)msg.obj);
}
} else if (msg.what==MessageType.MESSAGE_DEVICE_NAME.getValue()) {
activity.setDeviceName((String) msg.obj);
}
}
}
}
private void startDeviceListActivity() {
stopConnection();
startActivityForResult(new Intent(this, DeviceListActivity.class), REQUEST_CONNECT_DEVICE);
}
private void stopConnection() {
if (connector != null) {
connector.stop();
connector = null;
}
}
#Override
public boolean onSearchRequested() {
if (isAdapterReady()) {
startDeviceListActivity();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.device_control_activity, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (isAdapterReady() && (connector == null)) setupConnector(device);
}
break;
case REQUEST_ENABLE_BT:
pendingRequestEnableBt = false;
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "Bt not enabled", Toast.LENGTH_LONG).show();
}
break;
}
}
private void setupConnector(BluetoothDevice connectedDevice) {
stopConnection();
connector = new DeviceConnector(new DeviceData(connectedDevice, getString(R.string.empty_device_name)), mHandler);
connector.connect();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (isAdapterReady()) {
if (isConnected()) {
stopConnection();
} else {
startDeviceListActivity();
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void appendLog(String message) {
String msg = message.replaceAll("[\n\t\r ]*", "");
console.append(msg.length() + ": " + msg + "\n");
final int scrollAmount = console.getLayout().getLineTop(console.getLineCount()) - console.getHeight();
console.scrollTo(0, scrollAmount>0?scrollAmount:0);
delete(getCacheDir());
}
private boolean isConnected() {
return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
}
public static MainActivity getInstance() {
return instance;
}
public void delete(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
for (File f:file.listFiles()) {
delete(f);
}
}
}
}
}
this code is downloaded, it isn't mine, I just modified it.
Hi everyone..
I have used android Bluetooth chat application code in my application
I want pass a device name to another activity so i have saved my device name in public static variable when i select device name from list view same as android chat application.
After that i used this device name in another activity .With the help of this device name i Started BluetoothChatservice in second activity same as bluetooth chat standard code example.I didnt used this services in my mainactivity because I want connect device in my second activity
I have used Secure key only.But when i satarted this service sometimes connection connected with my another devices or sometimes not .
When i try for connection from both side connection connected.But first time it is not connect .I have used many things for service start like in onResume or ONStart or OnCreate but i am not success ed. MY english not good so please read carefully.
MY Main Activity Code=======
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mSearch;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static BluetoothAdapter mBluetoothAdapter = null;
private LinearLayout mLin_getView;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
// Set up the custom title
mLin_getView=(LinearLayout) findViewById(R.id.mLin_addView);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#SuppressLint("NewApi")
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
//if (mChatService == null)
setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
}
#SuppressLint("NewApi")
private void setupChat() {
Log.d(TAG, "setupChat()");
mSearch = (Button) findViewById(R.id.btn_search);
mSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
initilizeFiled();
/*Intent serverIntent = new Intent(BluetoothChat.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);*/
}
});
mOutStringBuffer = new StringBuffer("");
}
protected void initilizeFiled() {
// TODO Auto-generated method stub
Button scanButton = (Button) findViewById(R.id.button_scan);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#SuppressLint("NewApi")
#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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// 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);
}
}
}
};
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Log.d("Device Address", address);
connectDevice(address, true);
}
};
#SuppressLint("NewApi")
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
//if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
// The Handler that gets information back from the BluetoothChatService
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(String Address,boolean secure) {
// Get the device MAC address
String address = Address;
// Get the BLuetoothDevice object
// BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Const.deviceName=device;
Intent ib=new Intent(DashboardActivity.this,RemmoteActivity.class);
startActivity(ib);
}
}
Second Activity=========
private BluetoothAdapter mBluetoothAdapter = null;
private String mConnectedDeviceName = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
String TAG="Remmote";
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
ImageView Img_video, Img_camera, Img_song, Img_play, Img_forward,
Img_backward, Img_volume_up, Img_volume_down, Img_splash,
Img_capture, Img_zoom_in, Img_zoom_out;
private BluetoothChatService mChatService=null;
private StringBuffer mOutStringBuffer;
private BluetoothDevice device_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_screen);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mChatService=new BluetoothChatService(this,mHandler);
mOutStringBuffer=new StringBuffer("");
mOutStringBuffer=new StringBuffer("");
device_Name=Const.device;
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
initilizeField();
}
public void onStart() {
super.onStart();
Log.print(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public synchronized void onResume() {
super.onResume();
Log.print(TAG, "+ ON RESUME +");
mChatService.connect(device_Name, true);
}
#Override
public synchronized void onPause() {
super.onPause();
Log.print(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
Log.print(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
Log.print(TAG, "--- ON DESTROY ---");
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mImg_camera:
sendMessage("Camera");
break;
case R.id.mImg_video:
break;
case R.id.mImg_songs:
break;
case R.id.Img_play:
break;
case R.id.Img_forward:
break;
case R.id.Img_backward:
break;
case R.id.Img_volume_up:
break;
default:
break;
}
}
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
// mOutEditText.setText(mOutStringBuffer);77
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Const.Camera:
com.example.utils.Log.print("your tab is here====="+1000);
//BluetoothChat.this.sendMessage("Camera");
break;
case MESSAGE_STATE_CHANGE:
Log.print(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "STATE_CONNECTED", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "STATE_CONNECTING", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
Toast.makeText(getApplicationContext(), "STATE_NOT_LISTEN", Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
Toast.makeText(getApplicationContext(), writeMessage, Toast.LENGTH_SHORT).show();
//mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Toast.makeText(getApplicationContext(), "Read", Toast.LENGTH_SHORT).show();
// captureImage();
// mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
In const Class for public static varible
public static BluetoothDevice device;
BluetoothChatService Code Same as android default program example
I'm developing an app, where I have a button wich displays a dialog Activity where it finds bluetooth devices.
It works fine, but if I press de back button while in this activity, instead of returning to the main activity, it destroys it.
The dialog activity is the same that in the BluetoothChat example. This is the code of the main activity:
/*********************
*
* ONCREATE
*
********************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
/**Call to the Configuration activity*/
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanzarConfiguracion (null);
}
});
/**Call to the DeviceList activity*/
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanzarBusqueda (null);
}
});
GlobalVar.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (GlobalVar.mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
/*********************
*
* ONSTART
*
********************/
#Override
public void onStart() {
super.onStart();
if (!GlobalVar.mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, GlobalVar.REQUEST_ENABLE_BT);
}
else {
if (GlobalVar.mTransmission == null) setupCaller();
}
}
/*********************
*
* ONDESTROY
*
********************/
#Override
public void onDestroy() {
super.onDestroy();
/**Stop the Bluetooth chat services*/
if (GlobalVar.mTransmission != null) GlobalVar.mTransmission.stop();
}
/*********************
*
* OPTIONS
*
********************/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/**Inflate the menu; this adds items to the action bar if it is present.*/
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.info:
lanzarInfo(null);
break;
case R.id.config:
lanzarConfiguracion(null);
break;
}
return true; /** true -> consumimos el item, no se propaga*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case GlobalVar.REQUEST_CONNECT_DEVICE:
/**When DeviceListActivity returns with a device to connect*/
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
case GlobalVar.REQUEST_ENABLE_BT:
/**When the request to enable Bluetooth returns*/
if (resultCode == Activity.RESULT_OK) {
/**Bluetooth is now enabled, so set up a chat session*/
setupCaller();
} else {
/**User did not enable Bluetooth or an error occurred*/
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
private void connectDevice(Intent data) {
/**Get the device MAC address*/
String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
/**Get the BluetoothDevice object*/
BluetoothDevice device = GlobalVar.mBluetoothAdapter.getRemoteDevice(address);
/**Attempt to connect to the device*/
try{
GlobalVar.mTransmission.connect(device);
}catch(Exception ex) {
}
}
private final void setStatus(int resId) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the Transmission
*/
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GlobalVar.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case GlobalVar.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, GlobalVar.mConnectedDeviceName));
GlobalVar.mCommunicationArrayAdapter.clear();
break;
case GlobalVar.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case GlobalVar.STATE_LISTEN:
case GlobalVar.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case GlobalVar.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
/**construct a string from the buffer*/
String writeMessage = new String(writeBuf);
GlobalVar.mCommunicationArrayAdapter.add("Me: " + writeMessage);
break;
case GlobalVar.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
/**construct a string from the valid bytes in the buffer*/
String readMessage = new String(readBuf, 0, msg.arg1);
GlobalVar.mCommunicationArrayAdapter.add(GlobalVar.mConnectedDeviceName+": " + readMessage);
break;
case GlobalVar.MESSAGE_DEVICE_NAME:
/**save the connected device's name*/
GlobalVar.mConnectedDeviceName = msg.getData().getString(GlobalVar.DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to " + GlobalVar.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case GlobalVar.MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(GlobalVar.TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
public void setupCaller() {
/**Initialize the Transmission to perform bluetooth connections*/
GlobalVar.mTransmission = new Transmission(this, mHandler);
/**Initialize the array adapter here for avoid errors with the Handler above*/
//GlobalVar.mCommunicationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
}
/*********************
*
* INTENTS
*
********************/
public void lanzarConfiguracion (View view) {
Intent i = new Intent (this, Configuration.class);
startActivity(i);
}
public void lanzarInfo (View view) {
Intent i = new Intent(this, Info.class);
startActivity(i);
}
public void lanzarBusqueda (View view) {
Intent serverintent = new Intent(this, DeviceListDialog.class);
startActivityForResult(serverintent, GlobalVar.REQUEST_CONNECT_DEVICE);
}
}
You forgot the break statement before
case GlobalVar.REQUEST_ENABLE_BT:
The execution continues in this case, and reaches the finish() statement because the default RESULT_CODE for back press is Activity.RESULT_CANCEL.