Android Studio: Textview in Bluetooth Chat sample - android

I am using Bluetooth Chat sample to receive Sensor Data from my Arduino on my Android Device. I'm trying to display the incoming message to a TextView. Here's my code for the Bluetooth Chat Fragment class
package com.example.android.bluetoothchat;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.common.logger.Log;
/**
* This fragment controls Bluetooth to communicate with other devices.
*/
public class BluetoothChatFragment extends Fragment {
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;
private TextView display;
/**
* 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
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// 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(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#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();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
#Override
public void onResume() {
super.onResume();
// 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.
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();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
display = (TextView) view.findViewById(R.id.kotak);
}
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
View view = getView();
if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(getActivity(), mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
/**
* Makes this device discoverable for 300 seconds (5 minutes).
*/
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), 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);
}
}
/**
* The action listener for the EditText widget, to listen for the return key
*/
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
/**
* Updates the status on the action bar.
*
* #param resId a string resource ID
*/
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(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);
mConversationArrayAdapter.add("Me: " + writeMessage);
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.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
display.setText(readMessage);
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
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);
}
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(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
/**
* Establish connection with other device
*
* #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);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}}
Problem is when I launched the application in my android, the app crashed after receiving bluetooth data. The report bug I get from the application is
java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at
com.example.android.bluetoothchat.BluetoothChatFragment$3.handleMessage(BluetoothChatFragment.java:315)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5442)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygotelnit$MethodAndArgsCaller.run(Zygotelnit.java:738)
at com.android.internal.os.Zygotelnit.main(Zygotelnit.java:628)
Can anybody help me for this problem? Thanks a lot

Remove this from your TextView textView = (TextView) view.findViewById(R.id.edit_text_out); from your mSendButton.setOnClickListener and intilize it it into your onViewCreated like below code
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
display = (TextView) view.findViewById(R.id.kotak);
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
}

Related

android PDF rendering issue

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);
}
}

Get the data from sensor and save it somewhere

I'm using a sensor connected via Bluetooth who sends info about heart rate, heart beat number, distance, speed and strides.
I've done it, it shows me info about that 5 facts but I don't know how to save them.The sensor sends info very often, about 1 time per second.
I must write it in SQLite and insert data with something that I think is called 'bulk insert' because it works faster than inserting every time the sensor sends data. So, the data must be saved somewhere until the bulk insert into SQLite.
This is my code so far which gets data in real time from the sensor:
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
public class hxmDemo extends Activity {
private static final String TAG = "hxmDemo";
private TextView mTitle;
private TextView mStatus;
private String mHxMName = null;
private String mHxMAddress = null;
private BluetoothAdapter mBluetoothAdapter = null;
private HxmService mHxmService = null;
private void connectToHxm() {
mStatus.setText(R.string.connecting);
if (mHxmService == null)
setupHrm();
if ( getFirstConnectedHxm() ) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mHxMAddress);
mHxmService.connect(device); // Attempt to connect to the device
} else {
mStatus.setText(R.string.nonePaired);
}
}
private boolean getFirstConnectedHxm() {
mHxMAddress = null;
mHxMName = null;
BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = mBtAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
for (BluetoothDevice device : bondedDevices) {
String deviceName = device.getName();
if ( deviceName.startsWith("HXM") ) {
mHxMAddress = device.getAddress();
mHxMName = device.getName();
Log.d(TAG,"getFirstConnectedHxm() found a device whose name starts with 'HXM', its name is "+mHxMName+" and its address is ++mHxMAddress");
break;
}
}
}
return (mHxMAddress != null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.rawdata);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
mTitle = (TextView) findViewById(R.id.title);
if ( mTitle == null ) {
Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
finish();
}
mStatus = (TextView) findViewById(R.id.status);
if ( mStatus == null ) {
Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
finish();
}
mTitle.setText(R.string.hxmDemoAppName);
mStatus.setText(R.string.initializing);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Intent intent = new Intent(this, WelcomeMessage.class);
startActivityForResult( intent , 1 );
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available or not enabled", Toast.LENGTH_LONG).show();
mStatus.setText(R.string.noBluetooth);
} else {
if (!mBluetoothAdapter.isEnabled()) {
mStatus.setText(R.string.btNotEnabled);
Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
} else {
mStatus.setText(R.string.connecting);
connectToHxm();
}
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart");
if (mBluetoothAdapter != null ) {
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
mStatus.setText(R.string.btNotEnabled);
Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
}
} else {
mStatus.setText(R.string.noBluetooth);
Log.d(TAG, "onStart: No blueooth adapter detected, it needs to be present and enabled");
}
}
#Override
public synchronized void onResume() {
super.onResume();
Log.d(TAG, "onResume");
// 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.
if (mHxmService != null) {
if (mHxmService.getState() == R.string.HXM_SERVICE_RESTING) {
// Start the Bluetooth scale services
mHxmService.start();
}
}
}
private void setupHrm() {
Log.d(TAG, "setupScale:");
// Initialize the service to perform bluetooth connections
mHxmService = new HxmService(this, mHandler);
}
#Override
public synchronized void onPause() {
super.onPause();
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mHxmService != null) mHxmService.stop();
Log.e(TAG, "--- ON DESTROY ---");
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case R.string.HXM_SERVICE_MSG_STATE:
Log.d(TAG, "handleMessage(): MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case R.string.HXM_SERVICE_CONNECTED:
if ((mStatus != null) && (mHxMName != null)) {
mStatus.setText(R.string.connectedTo);
mStatus.append(mHxMName);
}
break;
case R.string.HXM_SERVICE_CONNECTING:
mStatus.setText(R.string.connecting);
break;
case R.string.HXM_SERVICE_RESTING:
if (mStatus != null ) {
mStatus.setText(R.string.notConnected);
}
break;
}
break;
case R.string.HXM_SERVICE_MSG_READ: {
byte[] readBuf = (byte[]) msg.obj;
HrmReading hrm = new HrmReading( readBuf );
hrm.displayRaw();
break;
}
case R.string.HXM_SERVICE_MSG_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(null),Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
connectToHxm();
return true;
case R.id.quit:
finish();
return true;
case R.id.about: {
/*
* Start the activity that displays our welcome message
*/
Intent intent = new Intent(this, WelcomeMessage.class);
startActivityForResult( intent , 1 );
break;
}
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult " + requestCode);
switch(requestCode)
{
case 1:
break;
}
}
public class HrmReading {
public final int STX = 0x02;
public final int MSGID = 0x26;
public final int DLC = 55;
public final int ETX = 0x03;
private static final String TAG = "HrmReading";
int heartRate;
int heartBeatNumber;
long distance;
long speed;
byte strides;
public HrmReading (byte[] buffer) {
int bufferIndex = 0;
Log.d ( TAG, "HrmReading being built from byte buffer");
try {
heartRate = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
heartBeatNumber = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
distance = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
speed = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
strides = buffer[bufferIndex++];
} catch (Exception e) {
/*
* An exception should only happen if the buffer is too short and we walk off the end of the bytes,
* because of the way we read the bytes from the device this should never happen, but just in case
* we'll catch the exception
*/
Log.d(TAG, "Failure building HrmReading from byte buffer, probably an incopmplete or corrupted buffer");
}
Log.d(TAG, "Building HrmReading from byte buffer complete, consumed " + bufferIndex + " bytes in the process");
dump();
}
private void displayRaw() {
display ( R.id.heartRate, (int)heartRate );
display ( R.id.heartBeatNumber, (int)heartBeatNumber );
display ( R.id.distance, distance );
display ( R.id.speed, speed );
display ( R.id.strides, (int)strides );
}
public void dump() {
Log.d(TAG,"...heartRate "+ ( heartRate ));
Log.d(TAG,"...heartBeatNumber "+ ( heartBeatNumber ));
Log.d(TAG,"...distance "+ ( distance ));
Log.d(TAG,"...speed "+ ( speed ));
Log.d(TAG,"...strides "+ ( strides ));
}
private void display ( int nField, int d ) {
String INT_FORMAT = "%d";
String s = String.format(INT_FORMAT, d);
display( nField, s );
}
private void display ( int nField, long d ) {
String INT_FORMAT = "%d";
String s = String.format(INT_FORMAT, d);
display( nField, s );
}
private void display ( int nField, CharSequence str ) {
TextView tvw = (TextView) findViewById(nField);
if ( tvw != null )
tvw.setText(str);
}
}
}
Does anybody know how to do this?
Well there is few steps, which you have to make:
Create your own class by extending #SQLiteOpenHelper - it will help you to handle your data base
Override #onCreate method - it will were you will execute sql request to create data base. I recommend to move name of keys for columns where you will store above data as static ariables, e.g:
public static final class db {
public static final String DATABASE_TABLE = "data_table";
public static final String KEY_ID = "id";
public static final String KEY_HEART_RATE = "heart_rate";
public static final String KEY_HEART_BEAT_NUMBER = "heart_beat_number";
public static final String KEY_DISTANCE = "distance";
public static final String KEY_SPEED = "speed";
public static final String KEY_STRIDER = "strides";
public static final String CREATE_DATA_TABLE =
"CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
+ KEY_HEART_RATE + " TEXT NOT NULL, "
+ KEY_HEART_BEAT_NUMBER + " TEXT NOT NULL, "
+ KEY_DISTANCE + " TEXT NOT NULL, "
+ KEY_SPEED + " TEXT NOT NULL, "
+ KEY_STRIDER + " TEXT NOT NULL");
and #onCreate may looks like it:
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CSConfig.db.db.CREATE_DATA_TABLE);
} catch (SQLiteException e) {
//Can not create table:
}
}
3.Add method to insert yours data and call everytime when you need save data to db:
public final void insertNewData(String heartRate, String heartBeatNumber, String distance, String speed, String stider, ) {
ContentValues dataRowValues = new ContentValues();
dataRowValues.put(CSConfig.db.db.KEY_HEART_RATE, heartRate);
dataRowValues.put(CSConfig.db.db.KEY_HEART_BEAT_NUMBER, heartBeatNumber);
dataRowValues.put(CSConfig.db.db.KEY_DISTANCE, distance);
dataRowValues.put(CSConfig.db.db.KEY_SPEED, speed);
dataRowValues.put(CSConfig.db.db.KEY_STRIDER, strider);
insert(CSConfig.db.db.DATABASE_TABLE, null, dataRowValues);
}
PS. I've omitted details about opening access to database. You can find more details e.g. here

Problems saving a xml file in Android

I am trying to save an array list into a xml file in the internal storage using Xmlserializer. The app scans for BLE and when a Stop button is pressed it should save some parameters from the list of BLE that it has detected. It runs perfect and when I pressed the stop button it stops the scan and displays in the mobile screen a toast message that the xml file has been created successfully. However, when I seach for the xml file, it doesn´t appear anywhere as if it hasn´t been created. I don´t know the reason of this problem. Here is the code I have implemented:
package com.example.newblescan;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.xmlpull.v1.XmlSerializer;
import com.example.newblescan.R;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.example.newblescan.adapter.BleDevicesAdapter;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends ListActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 100;
private BleDevicesAdapter leDeviceListAdapter;
private BluetoothAdapter bluetoothAdapter;
private Scanner scanner;
private Save save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (bluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_scan, menu);
if (scanner == null || !scanner.isScanning()) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
leDeviceListAdapter.clear();
if (scanner == null) {
scanner = new Scanner(bluetoothAdapter, mLeScanCallback);
scanner.startScanning();
invalidateOptionsMenu();
}
break;
case R.id.menu_stop:
if (scanner != null) {
save = new Save(leDeviceListAdapter);
scanner.stopScanning();
try {
save.savedata();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanner = null;
invalidateOptionsMenu();
}
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!bluetoothAdapter.isEnabled()) {
final Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
init();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
finish();
} else {
init();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
if (scanner != null) {
scanner.stopScanning();
scanner = null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = leDeviceListAdapter.getDevice(position);
if (device == null)
return;
//final Intent intent = new Intent(this, DeviceServicesActivity.class);
//intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_NAME, device.getName());
//intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
//startActivity(intent);
}
private void init() {
if (leDeviceListAdapter == null) {
leDeviceListAdapter = new BleDevicesAdapter(getBaseContext());
setListAdapter(leDeviceListAdapter);
}
if (scanner == null) {
scanner = new Scanner(bluetoothAdapter, mLeScanCallback);
scanner.startScanning();
}
invalidateOptionsMenu();
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
leDeviceListAdapter.addDevice(device, rssi);
leDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
private static class Scanner extends Thread {
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothAdapter.LeScanCallback mLeScanCallback;
private volatile boolean isScanning = false;
Scanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) {
bluetoothAdapter = adapter;
mLeScanCallback = callback;
}
public boolean isScanning() {
return isScanning;
}
public void startScanning() {
synchronized (this) {
isScanning = true;
start();
}
}
public void stopScanning() {
synchronized (this) {
isScanning = false;
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
#Override
public void run() {
try {
while (true) {
synchronized (this) {
if (!isScanning)
break;
bluetoothAdapter.startLeScan(mLeScanCallback);
}
sleep(SCAN_PERIOD);
synchronized (this) {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
} catch (InterruptedException ignore) {
} finally {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
}
public class Save {
/**
*
*/
private BleDevicesAdapter leDeviceListAdapter;
Save(BleDevicesAdapter BLEList) {
leDeviceListAdapter = BLEList;
}
public void savedata() throws FileNotFoundException{
String filename = "Dragon.txt";
//String date = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
FileOutputStream fos = null;
int size = leDeviceListAdapter.getCount();
//Bundle extras = getIntent().getExtras();
//long timestamp = extras.getLong("currentTime");
try {
fos= openFileOutput(filename, Context.MODE_PRIVATE);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag("", "root");
//serializer.startTag("", "timestamp");
//serializer.text(date);
//serializer.endTag("", "timestamp");
for(int j = 0 ; j < size ; j++)
{
BluetoothDevice devices = leDeviceListAdapter.getDevice(j);
//Integer signal = leDeviceListAdapter.getRSSI(j);
serializer.startTag("", "name");
serializer.text(devices.getName());
serializer.endTag("", "name");
serializer.startTag("", "address");
serializer.text(devices.getAddress());
serializer.endTag("", "address");
//serializer.startTag(null, "rssi");
//serializer.setProperty(null, signal);
//serializer.endTag(null, "rssi");
}
//ObjectOutputStream out = new ObjectOutputStream(fos);
//out.write((int) timestamp);
//out.writeObject(leDeviceListAdapter);
//out.close();
serializer.endDocument();
serializer.flush();
fos.close();
Toast.makeText(DeviceScanActivity.this, R.string.list_saved, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
In the class Save, I implement the method savedata to save the list into a xml file.
Does anyone know what is the problem? Pleasee help!!!!
openFileOutput puts it in the /data/data/your_packagename/files directory. This directory can only be read by root and by your app- you will not be able to find the file in any other program without rooting your device. You will not be able to find it in a file explorer unless you have root access. If you want to be able to see the file, you need to write it somewhere world accessible, such as the sd card.

Bluetooth device name pass to another activity. Connection not connected in another activity

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

Issuing Intent to call activity along with parameters

I'm trying to send parameters string through putExtra function to the activity from the service, I have this code for my Server.java:
package com.winacro.andRHOME;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Server extends Service{
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
}
public void switchSpeaker(int hr, int min){
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
String sendMessage = "1";
/* Intent myIntent = new Intent(Server.this, andRHOME.class);
myIntent.putExtra("sendMessage","1");
startActivity(myIntent);
PendingIntent pi = PendingIntent.getService(Server.this, 0, myIntent, 0);
AlarmManager almmgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cldr = Calendar.getInstance();
int min1 = cldr.get(Calendar.MINUTE);
cldr.setTimeInMillis(System.currentTimeMillis());
cldr.add(Calendar.SECOND, 30);
almmgr.set(AlarmManager.RTC_WAKEUP, cldr.getTimeInMillis(), pi);*/
}
}
And This is the code for the Activity of whose sendMessage() method I want to access or pass in string variables too but My app is getting crashed, kindly help here!
package com.winacro.andRHOME;
import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
/**
* This is the main Activity that displays the current chat session.
*/
public class andRHOME extends Activity {
// Debugging
private static final String TAG = "andRHOME";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
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;
// 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;
String inp;
// Layout Views
private TextView mTitle;
//private ListView mConversationView;
//private EditText mOutEditText;
//private Button mSendButton;
private ToggleButton TB1;
private ToggleButton TB2;
private ToggleButton TB3;
private ToggleButton TB4;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
public StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
public BluetoothChatService mChatService = null;
#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);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// 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;
}
Bundle bundle = getIntent().getExtras();
inp = bundle.getString("sendMessage");
sendMessage(inp);
}
#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.
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();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
//mConversationView = (ListView) findViewById(R.id.in);
// mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
//mOutEditText = (EditText) findViewById(R.id.edit_text_out);
// mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
//mSendButton = (Button) findViewById(R.id.button_send);
/*mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
//TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = "0";
sendMessage(message);
}
});*/
TB1 = (ToggleButton) findViewById(R.id.toggleButton1);
TB1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB1.isChecked()){
String message = "1";
sendMessage(message);
} else if (!TB1.isChecked()){
String message = "6";
sendMessage(message);
}
}
});
TB2 = (ToggleButton) findViewById(R.id.ToggleButton01);
TB2.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB2.isChecked()){
String message = "0";
sendMessage(message);
} else if (!TB2.isChecked()){
String message = "5";
sendMessage(message);
}
}
});
TB3 = (ToggleButton) findViewById(R.id.ToggleButton02);
TB3.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB3.isChecked()){
String message = "2";
sendMessage(message);
} else if (!TB3.isChecked()){
String message = "7";
sendMessage(message);
}
}
});
TB4 = (ToggleButton) findViewById(R.id.ToggleButton03);
TB4.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB4.isChecked()){
String message = "3";
sendMessage(message);
} else if (!TB4.isChecked()){
String message = "8";
sendMessage(message);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#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 ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* #param message A string of text to send.
*/
private 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);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
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);
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;
}
}
};
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(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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.timer:
// Launch the DeviceListActivity to see devices and do scan
Intent myIntent = new Intent("com.winacro.andRHOME.Timer");
startActivity(myIntent);
return true;
/*case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;*/
}
return false;
}
}

Categories

Resources