Hi,
I'm new in this forum so I don't know if i'm in the correct section...
I created this class named BLEConnection becuase i'm tring to connect to a esp32 via BLE but i'm having some problem in the connection part... the class:
Java:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class BLEConnection {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private String mTargetDeviceAddress;
private boolean mScanning;
private BLEConnectionListener mListener;
private BluetoothGatt mBluetoothGatt;
private Context mContext;
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
// This callback is invoked when the connection state changes, e.g. from disconnected to connected.
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.e("bleee", "connected ");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e("bleee", "disconected");
}
}
};
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) { // This callback is invoked when a BLE advertisement is found.
Log.e("bleee", "scan result");
BluetoothDevice device = result.getDevice();
if (device.getAddress().equals(mTargetDeviceAddress)) {
Log.e("bleee", "device found 1");
mBluetoothLeScanner.stopScan(mScanCallback);
mScanning = false;
mListener.onDeviceFound(device);
}
}
@Override
public void onBatchScanResults(List<ScanResult> results) { // This callback is invoked when multiple BLE advertisements are found at once.
Log.e("bleee", "scan result multiple");
for (ScanResult result : results) {
BluetoothDevice device = result.getDevice();
if (device.getAddress().equals(mTargetDeviceAddress)) {
Log.e("bleee", "batch scan multiple");
mBluetoothLeScanner.stopScan(mScanCallback);
mScanning = false;
mListener.onDeviceFound(device);
break;
}
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e("bleee", "scan failed 1");
mScanning = false;
mListener.onScanFailed(errorCode);
}
};
public BLEConnection(Context context, String targetDeviceAddress, BLEConnectionListener listener) {
mTargetDeviceAddress = targetDeviceAddress;
mListener = listener;
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
public void startScan() {
Log.e("bleee", "starting scan..................");
if (mScanning) {
return;
}
List<ScanFilter> filters = new ArrayList<>();
ScanFilter filter = new ScanFilter.Builder()
.setDeviceAddress(mTargetDeviceAddress)
.build();
filters.add(filter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
.setReportDelay(0L)
.build();
mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
mScanning = true;
Log.e("bleee", "finished?");
}
public void stopScan() {
Log.e("bleee", "something stopped the scan");
if (mScanning) {
mBluetoothLeScanner.stopScan(mScanCallback);
mScanning = false;
}
}
public void writeMessage(byte[] message) {
Log.e("bleee", "writing message...............");
if (mBluetoothGatt == null) {
return;
}
BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("4fafc201-1fb5-459e-8fcc-c5c9c331914b"));
if (service == null) {
return;
}
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("beb5483e-36e1-4688-b7f5-ea07361b26a8"));
if (characteristic == null) {
return;
}
characteristic.setValue(message);
mBluetoothGatt.writeCharacteristic(characteristic);
}
public interface BLEConnectionListener {
void onDeviceFound(BluetoothDevice device);
void onScanFailed(int errorCode);
}
public void connectToDevice(BluetoothDevice device) {
Log.e("bleee", "Trying connecting");
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
}
public void disconnectFromDevice() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
}
please ignore that android studio thinks that some code is an error (because could not be safe and could crash if Bluetooth is not enable, but i'll skip for now this).
So now, I have a service that is this (eliminated useless method for my problem):
Java:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
//import com.welie.blessed.*;
public class SendNotifyService extends Service implements BLEConnection.BLEConnectionListener {
private volatile boolean shouldStopThread;
private volatile boolean oksend = false;
private String ESP32_MAC_ADDRESS = "84:F7:03:68:06:52";
private BLEConnection mBLEConnection;
public SendNotifyService() {}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldStopThread = false;
mBLEConnection = new BLEConnection(this, ESP32_MAC_ADDRESS, this);
// Start scanning for the device
mBLEConnection.startScan();
new Thread(new Runnable() {
@Override
public void run() {
while (!shouldStopThread) {
//-----------------------------------------------------------------------------------------------------
if(oksend == true){
byte[] message = "Hello, device!".getBytes();
mBLEConnection.writeMessage(message);
}
Log.e("Service Ard_OS", "Service is running...");
Log.e("Service Ard_OS", mac);
pause(4000);
//-----------------------------------------------------------------------------------------------------
}}
public void pause(int millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } }
}).start();
return START_STICKY;
}
@Override
public void onDeviceFound(BluetoothDevice device) {
Log.e("bleee", "device found 2");
oksend = true;
mBLEConnection.connectToDevice(device);
}
@Override
public void onScanFailed(int errorCode) {
Log.e("bleee", "scan failed, i think...");
}
}
Now it comes the problem:
Obviously I'm using a real phone (samsung galaxy a20e) that runs API 30.
When I start the Service in the LOGCAT using the filter "bleee" i can only see theese two debug message:
------------------ PROCESS STARTED (9353) for package com.example.ard_os ------------------
2023-01-03 22:52:02.993 9353-9353 bleee com.example.ard_os E starting scan..................
2023-01-03 22:52:03.012 9353-9353 bleee com.example.ard_os E finished?
Click to expand...
Click to collapse
So the problem is that i don't get nothing else, not in the BluetoothGattCallback and not even in the ScanCallback. It doesn't connect to the device... If I was not clear about something I will answer!
Thanks to everyone.
I fixed, while this functions were called in a Service I needed the ACCESS_BACKGROUND_LOCATION to scan... So my manifest is now:
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" android:maxSdkVersion="30" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
rember that some of these permissions needs the user approvment, so you need the Run Time Permission.
table with needed permissions to scan:
18 to 22 (No runtime permissions needed)
23 to 28 One of below:
- android.permission.ACCESS_COARSE_LOCATION
- android.permission.ACCESS_FINE_LOCATION
29 to 30 - android.permission.ACCESS_FINE_LOCATION
- android.permission.ACCESS_BACKGROUND_LOCATION*
31 to current - android.permission.BLUETOOTH_SCAN
- android.permission.ACCESS_FINE_LOCATION**
* Needed if scan is performed in background
** Only needed if you want to obtain user's location with BLE scanning (BLUETOOTH_SCAN is not using neverForLocation attribute in your App)
Related
I'm programming a simple Bluetooth client to send and receive text messages throught RFCOMM as a serial port. I had a look at the Android SDK tutorials and did it in the same way: an Activity which calls a thread to make the connection, and once done, another thread to take care of msg reception.
I'm trying to connect to a Parallax EasyBluetooth. Connection works all right between computer and EasyBT, and also between a Java based mobile and the EasyBT. So the problem must be at the code or, I hope not, at the Android mobile bluetooth chip. Anyway it gets on and off, and detects other devices when scanning, so I guess problem is just my coding.
The problem is that the code gets stuck at the connect() method. So let's see if anyone knows why.
The XML for the activity is simple:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/boton"
android:id="@+id/boton_enviar"
/>
</LinearLayout>
Of course I have added the bluetooth permissions to the Manifiest:
Code:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
And the code is the following:
Code:
package uniovi.PFC;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
public class PruebaBTActivity extends Activity {
private String TAG = "pruebaBT";
private BluetoothAdapter mBluetoothAdapter;
private Map<String, BluetoothDevice> mArrayAdapter;
private ConnectedThread hiloEscuchas;
private ConnectThread hiloConectando;
private Handler mHandler;
private Button botonEnviar;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
private static final int MESSAGE_READ = 1;
private byte bytes_enviar[];
private String cmd;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(TAG, "On create abriendo");
mArrayAdapter = new HashMap<String, BluetoothDevice>();
botonEnviar = (Button)findViewById(R.id.boton_enviar);
botonEnviar.setEnabled(false);
botonEnviar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
cmd = "A";
bytes_enviar = cmd.getBytes();
hiloEscuchas.write(bytes_enviar);
}
});
Log.d(TAG, "On create cerrando");
}
@Override
public void onResume() {
super.onResume();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.d(TAG, "Device does not support Bluetooth");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.put(device.getName(), device);
}
}
BluetoothDevice device = mArrayAdapter.get("EasyBT");
hiloConectando = new ConnectThread(device);
hiloConectando.run();
//while(hiloEscuchas.isConnected()==false);
//botonEnviar.setEnabled(true);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
hiloEscuchas = new ConnectedThread(mmSocket);
hiloEscuchas.run();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean conectado;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
conectado = false;
mHandler = new Handler();
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
conectado = true;
}
public boolean isConnected(){
return conectado;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
cmd = "A";
bytes_enviar = cmd.getBytes();
hiloEscuchas.write(bytes_enviar);
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main Activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
There was some code to make a bluetooth scan for devices, but in order to get things simple until it works, I wrote the MAC address manually into a variable. Comments explain this, and also shows where it gets stuck.
Thanks
Can anybody please help me with this? I'm stuck and I need Bluetooth connection working for my thesys
I have currently created a simple tcp socket client application that sends and receives messages from a dotnet server application I have created. The application itself actually works however there are a few things I would like to know if they are possible or not. Also this is my first ever droid application and my first ever java application so I am sure there is a better way to do what I have written so please go easy on me.
The problem that I am having is I need a way to monitor the status of the socket so that if the connection gets dropped whether it is from the server application ending or a network drop that the android client would disconnect and put a notification on the screen letting me know. Currently if I end the server application nothign happens on the client and it acts like the connection is still open. Granted this is probably due to the way I have it written so I am looking for samples or suggestions on how to change this so I can monitor this. Any help would be great. Eventually this will be put into a much larger project for my home but I am starting off small so I can do it correctly the first time rather than having someing messy later on.
My code is listed below.
Thanks
KJ
Source:
package com.kkearney.tcp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TCPClient1Activity extends Activity {
public static final int BUFFER_SIZE = 2048;
private Socket sck = null;
private PrintWriter out = null;
private BufferedReader in = null;
Button btnSend;
Button btnConnect;
Button btnDisconnect;
EditText textOut;
TextView textIn;
String response = "";
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
textIn.setText(response);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.txtSend);
textIn = (TextView)findViewById(R.id.txtMSG);
btnSend = (Button)findViewById(R.id.btnSend);
btnConnect = (Button)findViewById(R.id.btnConnect);
btnDisconnect = (Button)findViewById(R.id.btnDisconnect);
}
public void ConnectUp(View view){
OpenConnection();
}
public void OpenConnection(){
new Thread(new Runnable(){
public void run(){
try{
if (sck == null){
sck = new Socket("10.0.0.135",8080);
sck.setKeepAlive(true);
screenConfig();
in = new BufferedReader(new InputStreamReader(sck.getInputStream()));
out = new PrintWriter(sck.getOutputStream());
sendDataWithString("testing 1 2 3");
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
response += new String(buffer).substring(0, charsRead);
handler.post( updateUI );
}
screenConfig();
}
}
catch (IOException e) {
System.out.print(e+"");
}
catch (Exception e) {
System.out.print(e+"");
}
}
}).start();
}
public void screenConfig(){
if (sck.isClosed() == false){
textOut.setClickable(true);
btnSend.setClickable(true);
btnDisconnect.setClickable(true);
btnConnect.setClickable(false);
}else{
textOut.setClickable(false);
btnSend.setClickable(false);
btnDisconnect.setClickable(false);
btnConnect.setClickable(true);
}
}
public void SendMessage(View view){
sendDataWithString(textOut.getText().toString());
textOut.setText(null);
}
public void DisConnect(View view){
CloseConnection();
}
public void CloseConnection(){
if (sck != null) {
try {
sck.close();
screenConfig();
} catch (IOException e) {
e.printStackTrace();
} finally {
sck = null;
}
}
}
public void sendDataWithString(String message) {
if (message != null && sck != null) {
out.write(message);
out.flush();
}
}
}
this is my server code
i am getting an error on my android phone when i clicked the device address
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class ServerSide {
//private static LocalDevice localDevice;
static LocalDevice localDevice;
DiscoveryAgent agent;
private void startServer() throws IOException{
UUID uuid = new UUID("112f8dbf1e46442292b6796539467bc9", false);
String connectionString = "btspp://localhost:" + uuid
+";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
System.out.println("\nServer Started. Waiting for clients to
connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address:
"+dev.getBluetoothAddress());
System.out.println("Remote device name:
"+dev.getFriendlyName(true));
}
public static void main(String[] args) {
//display local device address and name
try{
localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
try{
ServerSide sampleSPPServer=new ServerSide();
sampleSPPServer.startServer();
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
}
}
**************************************************************
and this is my client(android) code
package client.side;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ClientSideActivity extends Activity {
int REQUEST_ENABLE_BT = 0;
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mArrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
final ListView lv1 = (ListView)findViewById(R.id.listView1);
final TextView out = (TextView)findViewById(R.id.textView1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
}
out.setText(null);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
out.setText("Paired Devices");
Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
mArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
}
lv1.setAdapter(mArrayAdapter);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.setText("Discovered Devices");
mBluetoothAdapter.startDiscovery();
Toast msg = Toast.makeText(ClientSideActivity.this, "Discovering
Devices please wait.", Toast.LENGTH_LONG);
msg.show();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
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);
// Add the name and address to an array adapter to show
in a ListView
mArrayAdapter.add(device.getAddress());
} }
};
// Register the BroadcastReceiver
IntentFilter filter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister
during onDestroy
}
});
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,long id)
{
out.setText(arg0.getItemAtPosition(position).toString());
BluetoothDevice remoteDev = (BluetoothDevice)
arg0.getItemAtPosition(position);
ConnectThread conDev = new ConnectThread(remoteDev);
conDev.start();
}
});
}
public class ConnectThread extends Thread {
private final UUID MY_UUID =
UUID.fromString("112f8dbf1e46442292b6796539467bc9");
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to
mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the
server code
tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the
connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will
block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate
thread)
}
/** Will cancel an in-progress connection, and close the
socket */
}
}
Code:
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class RSSListAdapter extends BaseAdapter {
private Context mContext;
private List<rssnewsitem> mItems = new ArrayList<rssnewsitem>();
public RSSListAdapter(Context context) {
mContext = context;
}
public void addItem(RSSNewsItem it) {
mItems.add(it);
}
public void setListItems(List<rssnewsitem> lit) {
mItems = lit;
}
public int getCount() {
return mItems.size();
}
public Object getItem(int position) {
return mItems.get(position);
}
public boolean areAllItemsSelectable() {
return false;
}
public boolean isSelectable(int position) {
return true;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
RSSNewsItemView itemView;
if (convertView == null) {
itemView = new RSSNewsItemView(mContext, mItems.get(position));
} else {
itemView = (RSSNewsItemView) convertView;
itemView.setIcon(mItems.get(position).getIcon());
itemView.setText(0, mItems.get(position).getTitle());
itemView.setText(1, mItems.get(position).getPubDate());
itemView.setText(2, mItems.get(position).getCategory());
itemView.setText(3, mItems.get(position).getDescription());
}
return itemView;
[B][COLOR="Red"] }[/COLOR][/B]
}
</rssnewsitem></rssnewsitem></rssnewsitem>
Error :
1. rssnewsitem cannot be resolved to a type.
2. insert "}" to complete classbody.{the red one on code}
I am practicing parsing with android and these sources are available on here.
However, eclipse is outputing error like above.
If I change rssnewsitem to RSSNewsItem, error 1 disappears.
However I could not understand even if I use "Clean" option or insert }, the error doesn't disappear.
} problem are also available on here.
Thank you.
Hi i have problem capturing the information using the facebook SDK.
The console dont show any error but capture nothing.
In this code below i want to capture the name provided by the facebook SDK
Code:
package com.eduardoh89saluguia;
import java.util.List;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("unused")
public class Registro extends Activity {
String get_id, get_name, get_gender, get_email, get_birthday, get_locale, get_location;
private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String LOG_TAG = null;
// do something with <response> now
try{
// get_id = user.getId();
get_name = user.getName();
//get_gender = (String) user.getProperty("gender");
//get_email = (String) user.getProperty("email");
//get_birthday = user.getBirthday();
//get_locale = (String) user.getProperty("locale");
//get_location = user.getLocation().toString();
Log.d(LOG_TAG, user.getId() + "; " +
user.getName() + "; " //+
//(String) user.getProperty("gender") + "; " +
//(String) user.getProperty("email") + "; " +
//user.getBirthday()+ "; " +
//String) user.getProperty("locale") + "; " +
//user.getLocation()
);
TextView temp;
temp =(TextView)findViewById(R.id.edit1);
temp.setText("your name is "+get_name);
} catch(Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(), Ejecucion.class);
startActivity(i);
}
});
}
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
String LOG_TAG = null;
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registro, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}