How to send file using bluetooth on android programatically? - android

I need to send file to a computer instead of another android application. I have looked at the bluetooth api, but it only allow connection as client-server. In my case I dont know what UUId would be on the computer. Do I need to look at obex. I haven't used it before. So any help would be benficial.

Try this.
I can send a file using this code.
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, "file:///sdcard/refresh.txt");
values.put(BluetoothShare.DESTINATION, deviceAddress);
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
Code of BluetoothShare.java
import android.provider.BaseColumns;
import android.net.Uri;
/**
* Exposes constants used to interact with the Bluetooth Share manager's content
* provider.
*/
public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {
}
/**
* The permission to access the Bluetooth Share Manager
*/
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";
/**
* The content:// URI for the data table in the provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://com.android.bluetooth.opp/btopp");
/**
* Broadcast Action: this is sent by the Bluetooth Share component to
* transfer complete. The request detail could be retrieved by app * as _ID
* is specified in the intent's data.
*/
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";
/**
* This is sent by the Bluetooth Share component to indicate there is an
* incoming file need user to confirm.
*/
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";
/**
* This is sent by the Bluetooth Share component to indicate there is an
* incoming file request timeout and need update UI.
*/
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";
/**
* The name of the column containing the URI of the file being
* sent/received.
*/
public static final String URI = "uri";
/**
* The name of the column containing the filename that the incoming file
* request recommends. When possible, the Bluetooth Share manager will
* attempt to use this filename, or a variation, as the actual name for the
* file.
*/
public static final String FILENAME_HINT = "hint";
/**
* The name of the column containing the filename where the shared file was
* actually stored.
*/
public static final String _DATA = "_data";
/**
* The name of the column containing the MIME type of the shared file.
*/
public static final String MIMETYPE = "mimetype";
/**
* The name of the column containing the direction (Inbound/Outbound) of the
* transfer. See the DIRECTION_* constants for a list of legal values.
*/
public static final String DIRECTION = "direction";
/**
* The name of the column containing Bluetooth Device Address that the
* transfer is associated with.
*/
public static final String DESTINATION = "destination";
/**
* The name of the column containing the flags that controls whether the
* transfer is displayed by the UI. See the VISIBILITY_* constants for a
* list of legal values.
*/
public static final String VISIBILITY = "visibility";
/**
* The name of the column containing the current user confirmation state of
* the transfer. Applications can write to this to confirm the transfer. the
* USER_CONFIRMATION_* constants for a list of legal values.
*/
public static final String USER_CONFIRMATION = "confirm";
/**
* The name of the column containing the current status of the transfer.
* Applications can read this to follow the progress of each download. See
* the STATUS_* constants for a list of legal values.
*/
public static final String STATUS = "status";
/**
* The name of the column containing the total size of the file being
* transferred.
*/
public static final String TOTAL_BYTES = "total_bytes";
/**
* The name of the column containing the size of the part of the file that
* has been transferred so far.
*/
public static final String CURRENT_BYTES = "current_bytes";
/**
* The name of the column containing the timestamp when the transfer is
* initialized.
*/
public static final String TIMESTAMP = "timestamp";
/**
* This transfer is outbound, e.g. share file to other device.
*/
public static final int DIRECTION_OUTBOUND = 0;
/**
* This transfer is inbound, e.g. receive file from other device.
*/
public static final int DIRECTION_INBOUND = 1;
/**
* This transfer is waiting for user confirmation.
*/
public static final int USER_CONFIRMATION_PENDING = 0;
/**
* This transfer is confirmed by user.
*/
public static final int USER_CONFIRMATION_CONFIRMED = 1;
/**
* This transfer is auto-confirmed per previous user confirmation.
*/
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;
/**
* This transfer is denied by user.
*/
public static final int USER_CONFIRMATION_DENIED = 3;
/**
* This transfer is timeout before user action.
*/
public static final int USER_CONFIRMATION_TIMEOUT = 4;
/**
* This transfer is visible and shows in the notifications while in progress
* and after completion.
*/
public static final int VISIBILITY_VISIBLE = 0;
/**
* This transfer doesn't show in the notifications.
*/
public static final int VISIBILITY_HIDDEN = 1;
/**
* Returns whether the status is informational (i.e. 1xx).
*/
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
/**
* Returns whether the transfer is suspended. (i.e. whether the transfer
* won't complete without some action from outside the transfer manager).
*/
public static boolean isStatusSuspended(int status) {
return (status == STATUS_PENDING);
}
/**
* Returns whether the status is a success (i.e. 2xx).
*/
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
/**
* Returns whether the status is an error (i.e. 4xx or 5xx).
*/
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
/**
* Returns whether the status is a client error (i.e. 4xx).
*/
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
/**
* Returns whether the status is a server error (i.e. 5xx).
*/
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
/**
* Returns whether the transfer has completed (either with success or
* error).
*/
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}
/**
* This transfer hasn't stated yet
*/
public static final int STATUS_PENDING = 190;
/**
* This transfer has started
*/
public static final int STATUS_RUNNING = 192;
/**
* This transfer has successfully completed. Warning: there might be other
* status values that indicate success in the future. Use isSucccess() to
* capture the entire category.
*/
public static final int STATUS_SUCCESS = 200;
/**
* This request couldn't be parsed. This is also used when processing
* requests with unknown/unsupported URI schemes.
*/
public static final int STATUS_BAD_REQUEST = 400;
/**
* This transfer is forbidden by target device.
*/
public static final int STATUS_FORBIDDEN = 403;
/**
* This transfer can't be performed because the content cannot be handled.
*/
public static final int STATUS_NOT_ACCEPTABLE = 406;
/**
* This transfer cannot be performed because the length cannot be determined
* accurately. This is the code for the HTTP error "Length Required", which
* is typically used when making requests that require a content length but
* don't have one, and it is also used in the client when a response is
* received whose length cannot be determined accurately (therefore making
* it impossible to know when a transfer completes).
*/
public static final int STATUS_LENGTH_REQUIRED = 411;
/**
* This transfer was interrupted and cannot be resumed. This is the code for
* the OBEX error "Precondition Failed", and it is also used in situations
* where the client doesn't have an ETag at all.
*/
public static final int STATUS_PRECONDITION_FAILED = 412;
/**
* This transfer was canceled
*/
public static final int STATUS_CANCELED = 490;
/**
* This transfer has completed with an error. Warning: there will be other
* status values that indicate errors in the future. Use isStatusError() to
* capture the entire category.
*/
public static final int STATUS_UNKNOWN_ERROR = 491;
/**
* This transfer couldn't be completed because of a storage issue.
* Typically, that's because the file system is missing or full.
*/
public static final int STATUS_FILE_ERROR = 492;
/**
* This transfer couldn't be completed because of no sdcard.
*/
public static final int STATUS_ERROR_NO_SDCARD = 493;
/**
* This transfer couldn't be completed because of sdcard full.
*/
public static final int STATUS_ERROR_SDCARD_FULL = 494;
/**
* This transfer couldn't be completed because of an unspecified un-handled
* OBEX code.
*/
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;
/**
* This transfer couldn't be completed because of an error receiving or
* processing data at the OBEX level.
*/
public static final int STATUS_OBEX_DATA_ERROR = 496;
/**
* This transfer couldn't be completed because of an error when establishing
* connection.
*/
public static final int STATUS_CONNECTION_ERROR = 497;
}

For Ice Cream Sandwich this code is not working so you have to use this code
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Intent sharingIntent = new Intent(
android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/jpeg");
sharingIntent
.setComponent(new ComponentName(
"com.android.bluetooth",
"com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(sharingIntent);
} else {
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, uri.toString());
Toast.makeText(getBaseContext(), "URi : " + uri,
Toast.LENGTH_LONG).show();
values.put(BluetoothShare.DESTINATION, deviceAddress);
values.put(BluetoothShare.DIRECTION,
BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI,
values);
}

You can use the obex library. It seemed that android didn't provide the obex library, but I solved the problem and the solution is posted here.
Further Explanation (please start reading from here if you're busy)
I was trying to create an android phone remote controller (and something similar to telnet server) which helps controlling the phone remotely with my old feature phone.
Main content :Bluetooth FTP client
My first plan was to make the app check the list of files of my feature phone's directory.
But I didn't know how to connect to my feature phone's ftp server.
I googled a lot about how to connect to a ftp server via bluetooth but I could only find that Bluetoorh FTP server used the OBEX Protocol.
I found a useful material (PDF file) in a SO thread and studied about OBEX connect requests, put and get operations.
So I finally wrote some codes that tries to connect to the Bluetooth FTP server. I want to show them to you, but I lost it :( The codes were like just directly writting byte sequences to the output stream.
I also had difficult time finding out what UUID makes the app connect as FTP client. But I tried every UUIDs retrieved using the code below.
String parcels="";
ParcelUuid[] uuids=mBtDevice.getUuids();
int i=0;
for (ParcelUuid p:uuids)
{
parcels += "UUID UUID" + new Integer(i).toString() + "=UUID.fromString((\"" + p.getUuid().toString() + "\"));\n\n";
++i;
}
Nothing seemed to bring me to the answer I wanted. So I googled more and found out that I not only should I use UUID 00001106-0000-1000-8000-00805f9b34fb to connect to OBEX FTP server, but also shold I transmit target header ** with UUID **F9EC7BC4-953C-11D2-984E-525400DC9E09 when sending OBEX connect request.
The code below shows how to connect to a bluetooth FTP server as a client.
try
{
mBtSocket = mBtDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(" 00001106-0000-1000-8000-00805f9b34fb"));
}
catch (Exception e)
{
//e.printStackTrace();
}
Thread thread=new Thread(new Runnable() {
public void run()
{
UUID uuid=UUID.fromString("F9EC7BC4-953C-11D2-984E-525400DC9E09");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
byte [] bytes=bb.array();
Operation putOperation=null;
Operation getOperation=null;
try
{
// connect the socket
mBtSocket.connect();
//I will explain below
mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));
HeaderSet headerset = new HeaderSet();
headerset.setHeader(HeaderSet.TARGET, bytes);
headerset = mSession.connect(headerset);
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
{
mConnected = true;
}
else
{
mSession.disconnect(headerset);
}
...
Then you are now connected as FTP client and are ready to use OBEX operations to send files, request for files, list directories, etc.
However I didn't want to wait an hour to send my command to my android phone. (And it would be inefficient if I increase frequency of polling, as every polling methods are.)
Start reading from here if you are busy
Main content: OBEX OPP
For the reason I mentioned above, I greedly searched for ways to manipulate OPP which I discovered from the OBEX documentation.
You may want to transfer files via bluetooth normally (without defining your protocol and building a new desktop application just for it) to your computer, right? Then sending to OBEX OPP inbox service that is running natively on your desktop windows computer is the best solution. So how can we connect to the OPP (Obex Object Push) inbox service?
Setup OBEX library
Add import javax.obex; to your source code.
If your compiler doesn't support OBEX library, download sources and add to your project from here.
Implement ObexTransport
You should provide a class that implements ObexTransport to the library when you use it. It defines how the library should send data (like by RFCOMM, TCP,...). A sample implementation is here. This can cause some runtime or compilation errors such as there's no method. But you can partially fix those by replacing the method calls to constants like return 4096 instead of return mSocket.getMaxTransmitPacketSize();, outcommenting the if statements of public int getMaxTransmitPacketSize(). Or you can try using reflection to get those methods runtime.
Get BluetoothSocket
Get a bluetooth socket using mBtDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(" 00001105-0000-1000-8000-00805f9b34fb" )); And call connect().
Create ClientSession
Create a instance of your ObexTransport implementation, and create a new ClientSession like mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));.
Send OBEX connect request to your computer OPP inbox service.
HeaderSet headerset = new HeaderSet();
// headerset.setHeader(HeaderSet.COUNT,n);
headerset = mSession.connect(null);
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
{
mConnected = true;
}
Send OBEX put requests using the ClientSession.
protected boolean Put(ClientSession session, byte[] bytes, String as, String type)
{
// TODO: Implement this method
//byte [] bytes;
String filename=as;
boolean retry=true;
int times=0;
while (retry && times < 4)
{
Operation putOperation=null;
OutputStream mOutput = null;
//ClientSession mSession = null;
//ArrayUtils.reverse(bytes);
try
{
// Send a file with meta data to the server
final HeaderSet hs = new HeaderSet();
hs.setHeader(HeaderSet.NAME, filename);
hs.setHeader(HeaderSet.TYPE, type);
hs.setHeader(HeaderSet.LENGTH, new Long((long)bytes.length));
Log.v(TAG,filename);
//Log.v(TAG,type);
Log.v(TAG,bytes.toString());
putOperation = session.put(hs);
mOutput = putOperation.openOutputStream();
mOutput.write(bytes);
mOutput.close();
putOperation.close();
}
catch (Exception e)
{
Log.e(TAG, "put failed", e);
retry = true;
times++;
continue;
//e.printStackTrace();
}
finally
{
try
{
if(mOutput!=null)
mOutput.close();
if(putOperation!=null)
putOperation.close();
}
catch (Exception e)
{
Log.e(TAG, "put finally" , e);
retry = true;
times++;
continue;
}
//updateStatus("[CLIENT] Connection Closed");
}
retry = false;
return true;
}
return false;
}
Finally, disconnect.
private void FinishBatch(ClientSession mSession) throws IOException
{
mSession.disconnect(null);
try
{
Thread.sleep((long)500);
}
catch (InterruptedException e)
{}
mBtSocket.close();
}
Then here is a wrapper class.
import android.bluetooth.*;
import android.util.*;
import java.io.*;
import java.util.*;
import javax.obex.*;
public class BluetoothOPPHelper
{
String address;
BluetoothAdapter mBtadapter;
BluetoothDevice device;
ClientSession session;
BluetoothSocket mBtSocket;
protected final UUID OPPUUID=UUID.fromString(("00001105-0000-1000-8000-00805f9b34fb"));
private String TAG="BluetoothOPPHelper";
public BluetoothOPPHelper(String address)
{
mBtadapter=BluetoothAdapter.getDefaultAdapter();
device=mBtadapter.getRemoteDevice(address);
try
{
mBtSocket = device.createRfcommSocketToServiceRecord(OPPUUID);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public ClientSession StartBatch(int n)
{
ClientSession mSession = null;
// TODO: Implement this method
boolean retry=true;
int times=0;
while (retry && times < 4)
{
//BluetoothConnector.BluetoothSocketWrapper bttmp=null;
try
{
mBtSocket.connect();
//bttmp = (new BluetoothConnector(device,false,BluetoothAdapter.getDefaultAdapter(),Arrays.asList(new UUID[]{OPPUUID,OPPUUID, OPPUUID}))).connect();//*/ device.createInsecureRfcommSocketToServiceRecord(OPPUUID);
/*if(mBtSocket.isConnected())
{
mBtSocket.close();
}*/
}
catch (Exception e)
{
Log.e(TAG, "opp fail sock " + e.getMessage());
retry = true;
times++;
continue;
}
try
{
//mBtSocket=bttmp.getUnderlyingSocket();
// mBtSocket.connect();
BluetoothObexTransport mTransport = null;
mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));
HeaderSet headerset = new HeaderSet();
// headerset.setHeader(HeaderSet.COUNT,n);
headerset = mSession.connect(null);
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
{
boolean mConnected = true;
}
else
{
Log.e(TAG, "SEnd by OPP denied;");
mSession.disconnect(headerset);
times++;
continue;
}
}
catch (Exception e)
{
Log.e(TAG, "opp failed;" , e);
retry = true;
times++;
continue;
//e.rintStackTrace();
}
retry=false;
}
return mSession;
}
protected boolean Put(ClientSession session, byte[] bytes, String as, String type)
{
// TODO: Implement this method
//byte [] bytes;
String filename=as;
boolean retry=true;
int times=0;
while (retry && times < 4)
{
Operation putOperation=null;
OutputStream mOutput = null;
//ClientSession mSession = null;
//ArrayUtils.reverse(bytes);
try
{
// Send a file with meta data to the server
final HeaderSet hs = new HeaderSet();
hs.setHeader(HeaderSet.NAME, filename);
hs.setHeader(HeaderSet.TYPE, type);
hs.setHeader(HeaderSet.LENGTH, new Long((long)bytes.length));
Log.v(TAG,filename);
//Log.v(TAG,type);
Log.v(TAG,bytes.toString());
putOperation = session.put(hs);
mOutput = putOperation.openOutputStream();
mOutput.write(bytes);
mOutput.close();
putOperation.close();
}
catch (Exception e)
{
Log.e(TAG, "put failed", e);
retry = true;
times++;
continue;
//e.printStackTrace();
}
finally
{
try
{
if(mOutput!=null)
mOutput.close();
if(putOperation!=null)
putOperation.close();
}
catch (Exception e)
{
Log.e(TAG, "put finally" , e);
retry = true;
times++;
continue;
}
//updateStatus("[CLIENT] Connection Closed");
}
retry = false;
return true;
}
return false;
}
protected boolean Put(ClientSession s, OPPBatchInfo info)
{
return Put(s,info.data,info.as,info.type);
}
private void FinishBatch(ClientSession mSession) throws IOException
{
mSession.disconnect(null);
try
{
Thread.sleep((long)500);
}
catch (InterruptedException e)
{}
mBtSocket.close();
}
public boolean flush() throws IOException
{
if (sendQueue.isEmpty())
{
return true;
}
try
{
Thread.sleep((long)2000);
}
catch (InterruptedException e)
{}
ClientSession session=StartBatch(sendQueue.size());
if (session == null)
{
return false;
}
while (!sendQueue.isEmpty())
{
if (Put(session, sendQueue.remove()) == false)
{
Log.e(TAG, "Put failed");
}
}
FinishBatch(session);
return true;
}
Queue<OPPBatchInfo> sendQueue;
public boolean AddTransfer(String as,String mimetype,byte[] data)
{
return sendQueue.add(new OPPBatchInfo(as,mimetype,data));
}
class OPPBatchInfo
{
String as;
String type;
byte[] data;
public OPPBatchInfo(String as,String type,byte[] data)
{
this.as=as;
this.data=data;
this.type=type;
}
}
}

You need to implement FTP over OBEX. Once you implement the standard protocol and profile, your Android FTP implementation will inter-operate with virtually any Bluetooth FTP server. You'll also need to implement OPP for maximum inter-operability. The OBEX protocol is not so difficult to implement and the specs is freely available.

I know this question is old, but for anyone having to deal with this still:
With this library you can send files via OBEX and commands via RFCOMM:
https://github.com/ddibiasi/Funker
Once connected to your target device, you can manipulate its filesystem.
The following example sends a file:
val rxOBEX = RxObex(device)
rxOBEX
.putFile("rubberduck.txt", "text/plain", "oh hi mark".toByteArray(), "example/directory") // Name of file, mimetype, bytes of file, directory
.subscribeBy(
onComplete = {
Log.d(TAG, "Succesfully sent a testfile to device")
},
onError = { e ->
Log.e(TAG, "Received error!")
}
)
The library is built on Rx, so all calls are non blocking.

Related

Making a Bluetooth speaker with playback controls connected to phone

I am recently working on a project. The idea is to make a Bluetooth speaker which has playback controls like pause,play, next song on the speaker itself. The speaker is to be connected to the mobile phone via Bluetooth. Ultimately i wanted to achieve the button control(on speaker) of songs I play on mobile which is connected to speaker via Bluetooth.
I was able to make the speaker connected via Bluetooth to the phone and could play songs but the biggest challenge is i couldn't pause or forward the playlist on phone from speaker side. What i understood is that the speaker is able to receive signals from phone to play songs but how do i send a command(like next song via physical button) from the speaker to the phone(via a micro controller like arduino). I hope I stated my situation well. I came across idea like having multiple bluetooth pairing, custom programming of the BT module that i'll be using, etc.
I am open to all kinds of way this can be done and I really appreciate if anyone could recommend me the proper BT modules and micro-controller to be used.
About the BT module, I suggest you to use an HC-05. For the MCU, Arduino cannot be used to play music... so you should optain for Rasberry, but I am not sure. Also I never used it...
If you need some code similar, I mede an app for a greenhouse which displays temperature, humidity and light inside it.
If you wanna read these class in order: gitHub.
But I have to post the code, too: maybe I could delete the repo a day
BLTSocket class:
public class BLTSocket extends Service {
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static boolean isBtConnected = false;
private static BluetoothAdapter adapter = null;
private static BluetoothSocket socket = null;
private static InputStream is = null;
private static OutputStream os = null;
public BLTSocket(){
}
/**
* Constructor called when a bluetooth device has been clicked in the layout
* If the phone's bluetooth socket has not already connected , it tries to initialize
* the new connection with the one clicked.
* Get the stream and set #isBtConnected as true
*
* #param address - MAC address of the bluetooth device
*/
public BLTSocket(String address){
if (!isBtConnected || !socket.isConnected()) {
try {
adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = adapter.getRemoteDevice(address);
socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
socket.connect();
is = socket.getInputStream();
os = socket.getOutputStream();
isBtConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
HandlerThread handlerThread = new HandlerThread("SURVEYS_SERVICE", Process.THREAD_PRIORITY_BACKGROUND);
handlerThread.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
survey();
return START_STICKY;
}
/**
* This handler keeps updating the three surveys reading their current value
* from the bluetooth module's input stream.
* Set the the circular progress bar and the own text view below as the relative value
*/
Handler handler = new Handler();
Runnable runnable;
private void survey() {
runnable = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
byte[] survey = new byte[12];
try {
/*
Once got the current values of the three surveys,
it sets the relative progress bar and the text view
*/
if(is.read(survey) > 0){
for(int i = 0; i < 3; i++){
MainActivity.getProgressBars()[i].setProgress(survey[i]);
MainActivity.getTextViews()[i].setText(String.valueOf(survey[i]) + (i == 0 ? "°C" : '%'));
}
}
} catch (IOException e) {
e.printStackTrace();
return;
}
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
/**
* Called when the user click on the UPDATE SEED button
* on the popup menu of the ViewSeed layout
*
* Send to the HC-05 the new recommended values
*
* #param values
*/
public void updateSeed(int[] values){
try {
handler.removeCallbacks(runnable);
for(int value : values) {
os.write(value);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
handler.postDelayed(runnable, 2000);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Close the socket and set #isBtConnected as false when the app is closed or crashes
*/
#Override
public void onDestroy() {
try {
this.socket.close();
this.isBtConnected = false;
}catch (IOException e) {
e.printStackTrace();
}
}
}
BLTActivity:
public class BluetoothActivity extends AppCompatActivity {
ActivityBluetoothBinding activityBluetoothBinding;
private BluetoothAdapter adapter;
private Set<BluetoothDevice> pairedDevices;
private ListView listBLTDevice;
private TextView bltTV;
private BluetoothDevice deviceSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityBluetoothBinding = DataBindingUtil.setContentView(this, R.layout.activity_bluetooth);
activityBluetoothBinding.setSettings(MainActivity.loadSettings);
this.bltTV = findViewById(R.id.bltTV);
this.listBLTDevice = findViewById(R.id.listBLTDevices);
setBlt();
}
public static BLTSocket bltSocket;
private void setBlt(){
this.adapter = BluetoothAdapter.getDefaultAdapter();
//If the adapter is null, the user's phone hasn't a bluetooth radio
if(adapter != null){
if(!adapter.isEnabled()){
//If the bluetooth is disabled, it asks to the user to enable it
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
}
//The bonded devices are those ones which have already been compared
pairedDevices = adapter.getBondedDevices();
this.bltTV.setText(pairedDevices.size() + " Devices Found");
if(pairedDevices.size() > 0){
/*
* Create a new list of strings which every one contains the name of one compared
* bluetooth radio. The array list is given to the adapter.
*/
final ArrayList<String> arrayList = new ArrayList<>();
for (BluetoothDevice device : pairedDevices){
arrayList.add(device.getName());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, getListViewLayout(), arrayList);
this.listBLTDevice.setAdapter(adapter);
/*
When an item (string that represents a bluetooth radio) has been clicked,
its MAC address is given to the BLTSocket constructor, which will set
the opportune variable, objects and connects our radio with the selected one
*/
this.listBLTDevice.setOnItemClickListener( (parent, v, pos, id) -> {
deviceSelected = (BluetoothDevice) pairedDevices.toArray()[pos];
Toast.makeText(getApplicationContext(), "Device Selected: " + deviceSelected.getName() + "\n" + deviceSelected.getAddress(), Toast.LENGTH_SHORT).show();
bltSocket = new BLTSocket(deviceSelected.getAddress());
startService(new Intent(this, BLTSocket.class));
} );
}
}else{
Toast.makeText(getApplicationContext(), "Seems like your device hasn't any bluetooth adapter...", Toast.LENGTH_SHORT).show();
}
}
/**
* Called when setting the ArrayAdapter to chose list layout with the right color of the text
* If the user has the dark mode enabled, this method returns the white list and vice versa
*
* #return the id of the opportune listview layout
*/
private int getListViewLayout() {
return !MainActivity.loadSettings.isDarkMode() ? R.layout.listview_blacktext_layout : R.layout.listview_whitetext_layout;
}
}

How to programmatically connect with vpn server without using "Secret key"?

I want to connect with VPN server but I don't want to use secret key. Currently the code snippet i found to programmatically create vpn connection is as follows:
MyVpnClient:
package com.example.android.toyvpn;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.widget.TextView;
public class ToyVpnClient extends Activity {
public interface Prefs {
String NAME = "connection";
String SERVER_ADDRESS = "server.address";
String SERVER_PORT = "server.port";
String SHARED_SECRET = "shared.secret";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
final TextView serverAddress = (TextView) findViewById(R.id.address);
final TextView serverPort = (TextView) findViewById(R.id.port);
final TextView sharedSecret = (TextView) findViewById(R.id.secret);
final SharedPreferences prefs = getSharedPreferences(Prefs.NAME, MODE_PRIVATE);
serverAddress.setText(prefs.getString(Prefs.SERVER_ADDRESS, ""));
serverPort.setText(prefs.getString(Prefs.SERVER_PORT, ""));
sharedSecret.setText(prefs.getString(Prefs.SHARED_SECRET, ""));
findViewById(R.id.connect).setOnClickListener(v -> {
prefs.edit()
.putString(Prefs.SERVER_ADDRESS, serverAddress.getText().toString())
.putString(Prefs.SERVER_PORT, serverPort.getText().toString())
.putString(Prefs.SHARED_SECRET, sharedSecret.getText().toString())
.commit();
Intent intent = VpnService.prepare(ToyVpnClient.this);
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
});
findViewById(R.id.disconnect).setOnClickListener(v -> {
startService(getServiceIntent().setAction(ToyVpnService.ACTION_DISCONNECT));
});
}
#Override
protected void onActivityResult(int request, int result, Intent data) {
if (result == RESULT_OK) {
startService(getServiceIntent().setAction(ToyVpnService.ACTION_CONNECT));
}
}
private Intent getServiceIntent() {
return new Intent(this, ToyVpnService.class);
}
}
MyVpnConnection:
package com.example.android.toyvpn;
import static java.nio.charset.StandardCharsets.US_ASCII;
import android.app.PendingIntent;
import android.net.VpnService;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.concurrent.TimeUnit;
public class ToyVpnConnection implements Runnable {
/**
* Callback interface to let the {#link ToyVpnService} know about new connections
* and update the foreground notification with connection status.
*/
public interface OnEstablishListener {
void onEstablish(ParcelFileDescriptor tunInterface);
}
/** Maximum packet size is constrained by the MTU, which is given as a signed short. */
private static final int MAX_PACKET_SIZE = Short.MAX_VALUE;
/** Time to wait in between losing the connection and retrying. */
private static final long RECONNECT_WAIT_MS = TimeUnit.SECONDS.toMillis(3);
/** Time between keepalives if there is no traffic at the moment.
*
* TODO: don't do this; it's much better to let the connection die and then reconnect when
* necessary instead of keeping the network hardware up for hours on end in between.
**/
private static final long KEEPALIVE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(15);
/** Time to wait without receiving any response before assuming the server is gone. */
private static final long RECEIVE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(20);
/**
* Time between polling the VPN interface for new traffic, since it's non-blocking.
*
* TODO: really don't do this; a blocking read on another thread is much cleaner.
*/
private static final long IDLE_INTERVAL_MS = TimeUnit.MILLISECONDS.toMillis(100);
/**
* Number of periods of length {#IDLE_INTERVAL_MS} to wait before declaring the handshake a
* complete and abject failure.
*
* TODO: use a higher-level protocol; hand-rolling is a fun but pointless exercise.
*/
private static final int MAX_HANDSHAKE_ATTEMPTS = 50;
private final VpnService mService;
private final int mConnectionId;
private final String mServerName;
private final int mServerPort;
private final byte[] mSharedSecret;
private PendingIntent mConfigureIntent;
private OnEstablishListener mOnEstablishListener;
public ToyVpnConnection(final VpnService service, final int connectionId,
final String serverName, final int serverPort, final byte[] sharedSecret) {
mService = service;
mConnectionId = connectionId;
mServerName = serverName;
mServerPort= serverPort;
mSharedSecret = sharedSecret;
}
/**
* Optionally, set an intent to configure the VPN. This is {#code null} by default.
*/
public void setConfigureIntent(PendingIntent intent) {
mConfigureIntent = intent;
}
public void setOnEstablishListener(OnEstablishListener listener) {
mOnEstablishListener = listener;
}
#Override
public void run() {
try {
Log.i(getTag(), "Starting");
// If anything needs to be obtained using the network, get it now.
// This greatly reduces the complexity of seamless handover, which
// tries to recreate the tunnel without shutting down everything.
// In this demo, all we need to know is the server address.
final SocketAddress serverAddress = new InetSocketAddress(mServerName, mServerPort);
// We try to create the tunnel several times.
// TODO: The better way is to work with ConnectivityManager, trying only when the
// network is available.
// Here we just use a counter to keep things simple.
for (int attempt = 0; attempt < 10; ++attempt) {
// Reset the counter if we were connected.
if (run(serverAddress)) {
attempt = 0;
}
// Sleep for a while. This also checks if we got interrupted.
Thread.sleep(3000);
}
Log.i(getTag(), "Giving up");
} catch (IOException | InterruptedException | IllegalArgumentException e) {
Log.e(getTag(), "Connection failed, exiting", e);
}
}
private boolean run(SocketAddress server)
throws IOException, InterruptedException, IllegalArgumentException {
ParcelFileDescriptor iface = null;
boolean connected = false;
// Create a DatagramChannel as the VPN tunnel.
try (DatagramChannel tunnel = DatagramChannel.open()) {
// Protect the tunnel before connecting to avoid loopback.
if (!mService.protect(tunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
tunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
tunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
iface = handshake(tunnel);
// Now we are connected. Set the flag.
connected = true;
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(iface.getFileDescriptor());
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(iface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET_SIZE);
// Timeouts:
// - when data has not been sent in a while, send empty keepalive messages.
// - when data has not been received in a while, assume the connection is broken.
long lastSendTime = System.currentTimeMillis();
long lastReceiveTime = System.currentTimeMillis();
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
lastReceiveTime = System.currentTimeMillis();
}
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
// Ignore control messages, which start with zero.
if (packet.get(0) != 0) {
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
}
packet.clear();
// There might be more incoming packets.
idle = false;
lastSendTime = System.currentTimeMillis();
}
// If we are idle or waiting for the network, sleep for a
// fraction of time to avoid busy looping.
if (idle) {
Thread.sleep(IDLE_INTERVAL_MS);
final long timeNow = System.currentTimeMillis();
if (lastSendTime + KEEPALIVE_INTERVAL_MS <= timeNow) {
// We are receiving for a long time but not sending.
// Send empty control messages.
packet.put((byte) 0).limit(1);
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
lastSendTime = timeNow;
} else if (lastReceiveTime + RECEIVE_TIMEOUT_MS <= timeNow) {
// We are sending for a long time but not receiving.
throw new IllegalStateException("Timed out");
}
}
}
} catch (SocketException e) {
Log.e(getTag(), "Cannot use socket", e);
} finally {
if (iface != null) {
try {
iface.close();
} catch (IOException e) {
Log.e(getTag(), "Unable to close interface", e);
}
}
}
return connected;
}
private ParcelFileDescriptor handshake(DatagramChannel tunnel)
throws IOException, InterruptedException {
// To build a secured tunnel, we should perform mutual authentication
// and exchange session keys for encryption. To keep things simple in
// this demo, we just send the shared secret in plaintext and wait
// for the server to send the parameters.
// Allocate the buffer for handshaking. We have a hardcoded maximum
// handshake size of 1024 bytes, which should be enough for demo
// purposes.
ByteBuffer packet = ByteBuffer.allocate(1024);
// Control messages always start with zero.
packet.put((byte) 0).put(mSharedSecret).flip();
// Send the secret several times in case of packet loss.
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Wait for the parameters within a limited time.
for (int i = 0; i < MAX_HANDSHAKE_ATTEMPTS; ++i) {
Thread.sleep(IDLE_INTERVAL_MS);
// Normally we should not receive random packets. Check that the first
// byte is 0 as expected.
int length = tunnel.read(packet);
if (length > 0 && packet.get(0) == 0) {
return configure(new String(packet.array(), 1, length - 1, US_ASCII).trim());
}
}
throw new IOException("Timed out");
}
private ParcelFileDescriptor configure(String parameters) throws IllegalArgumentException {
// Configure a builder while parsing the parameters.
VpnService.Builder builder = mService.new Builder();
for (String parameter : parameters.split(" ")) {
String[] fields = parameter.split(",");
try {
switch (fields[0].charAt(0)) {
case 'm':
builder.setMtu(Short.parseShort(fields[1]));
break;
case 'a':
builder.addAddress(fields[1], Integer.parseInt(fields[2]));
break;
case 'r':
builder.addRoute(fields[1], Integer.parseInt(fields[2]));
break;
case 'd':
builder.addDnsServer(fields[1]);
break;
case 's':
builder.addSearchDomain(fields[1]);
break;
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad parameter: " + parameter);
}
}
// Create a new interface using the builder and save the parameters.
final ParcelFileDescriptor vpnInterface;
synchronized (mService) {
vpnInterface = builder
.setSession(mServerName)
.setConfigureIntent(mConfigureIntent)
.establish();
if (mOnEstablishListener != null) {
mOnEstablishListener.onEstablish(vpnInterface);
}
}
Log.i(getTag(), "New interface: " + vpnInterface + " (" + parameters + ")");
return vpnInterface;
}
private final String getTag() {
return ToyVpnConnection.class.getSimpleName() + "[" + mConnectionId + "]";
}
}
MyVpnService:
package com.example.android.toyvpn;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class ToyVpnService extends VpnService implements Handler.Callback {
private static final String TAG = ToyVpnService.class.getSimpleName();
public static final String ACTION_CONNECT = "com.example.android.toyvpn.START";
public static final String ACTION_DISCONNECT = "com.example.android.toyvpn.STOP";
private Handler mHandler;
private static class Connection extends Pair<Thread, ParcelFileDescriptor> {
public Connection(Thread thread, ParcelFileDescriptor pfd) {
super(thread, pfd);
}
}
private final AtomicReference<Thread> mConnectingThread = new AtomicReference<>();
private final AtomicReference<Connection> mConnection = new AtomicReference<>();
private AtomicInteger mNextConnectionId = new AtomicInteger(1);
private PendingIntent mConfigureIntent;
#Override
public void onCreate() {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Create the intent to "configure" the connection (just start ToyVpnClient).
mConfigureIntent = PendingIntent.getActivity(this, 0, new Intent(this, ToyVpnClient.class),
PendingIntent.FLAG_UPDATE_CURRENT);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_DISCONNECT.equals(intent.getAction())) {
disconnect();
return START_NOT_STICKY;
} else {
connect();
return START_STICKY;
}
}
#Override
public void onDestroy() {
disconnect();
}
#Override
public boolean handleMessage(Message message) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
if (message.what != R.string.disconnected) {
updateForegroundNotification(message.what);
}
return true;
}
private void connect() {
// Become a foreground service. Background services can be VPN services too, but they can
// be killed by background check before getting a chance to receive onRevoke().
updateForegroundNotification(R.string.connecting);
mHandler.sendEmptyMessage(R.string.connecting);
// Extract information from the shared preferences.
final SharedPreferences prefs = getSharedPreferences(ToyVpnClient.Prefs.NAME, MODE_PRIVATE);
final String server = prefs.getString(ToyVpnClient.Prefs.SERVER_ADDRESS, "");
final byte[] secret = prefs.getString(ToyVpnClient.Prefs.SHARED_SECRET, "").getBytes();
final int port;
try {
port = Integer.parseInt(prefs.getString(ToyVpnClient.Prefs.SERVER_PORT, ""));
} catch (NumberFormatException e) {
Log.e(TAG, "Bad port: " + prefs.getString(ToyVpnClient.Prefs.SERVER_PORT, null), e);
return;
}
// Kick off a connection.
startConnection(new ToyVpnConnection(
this, mNextConnectionId.getAndIncrement(), server, port, secret));
}
private void startConnection(final ToyVpnConnection connection) {
// Replace any existing connecting thread with the new one.
final Thread thread = new Thread(connection, "ToyVpnThread");
setConnectingThread(thread);
// Handler to mark as connected once onEstablish is called.
connection.setConfigureIntent(mConfigureIntent);
connection.setOnEstablishListener(new ToyVpnConnection.OnEstablishListener() {
public void onEstablish(ParcelFileDescriptor tunInterface) {
mHandler.sendEmptyMessage(R.string.connected);
mConnectingThread.compareAndSet(thread, null);
setConnection(new Connection(thread, tunInterface));
}
});
thread.start();
}
private void setConnectingThread(final Thread thread) {
final Thread oldThread = mConnectingThread.getAndSet(thread);
if (oldThread != null) {
oldThread.interrupt();
}
}
private void setConnection(final Connection connection) {
final Connection oldConnection = mConnection.getAndSet(connection);
if (oldConnection != null) {
try {
oldConnection.first.interrupt();
oldConnection.second.close();
} catch (IOException e) {
Log.e(TAG, "Closing VPN interface", e);
}
}
}
private void disconnect() {
mHandler.sendEmptyMessage(R.string.disconnected);
setConnectingThread(null);
setConnection(null);
stopForeground(true);
}
private void updateForegroundNotification(final int message) {
startForeground(1, new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_vpn)
.setContentText(getString(message))
.setContentIntent(mConfigureIntent)
.build());
}
}
The above code is from the following url:
https://android.googlesource.com/platform/development/+/master/samples/ToyVpn
I have tried but I am not getting any workaround without secret key. Please help.
Unfortunately, we don't have any further requirements / spec of your VPN server.
You might want to have a look at the OpenVPN or strongSwan VPN (open source) implementations to see if they can fit your requirements. The latter for example provides the following ways of authentication on Android (https://wiki.strongswan.org/projects/strongswan/wiki/androidvpnclient):
Only IKEv2 is supported
Client authentication is limited to:
EAP authentication based on username/password (EAP-MSCHAPv2, EAP-MD5, EAP-GTC)
RSA/ECDSA authentication with private key/certificate
EAP-TLS with private key/certificate (see 1.4.5 for limitations)

How to use ACR35 NFC Reader in Android

I'm new in developing with ACR or NFC Reader, especially for Android. And recently I need to use an ACR35 and I've got the SDK and the example from this acs official website. And It works just fine as an example.
And now I need to create an activity that will always be ready to check whether nfc card is tapped. But the problem is I don't know how to detect when the nfc card is tapped and I don't know what to do next, and I can't find the way out from the example as it detects nfc card when I touch the 'transmit' button, it doesn't do it automatically.
Please give me with example code.
Thanks for your answer.
A bit late, but it might help someone.
I have found following project on the git hub. It shows how to read tag id from the acr35
here
.
I have been using acr35 for some time to read the tag id. From my experience is a buggy device on Android. I tested around 10 devices and it worked only on 3...
I read from it every second. It returns results from the last card even though it is not present there anymore. Therefore; I have to reset it twice per every successful read and it takes around 6 seconds to get the device in reading state again... Also be very careful with multithreading.
My implementation based on mentioned project - added simple locking to stop querying the card after successfull reading + full device reset, filternig same uuid which was read in very short time after it was read previously:
ACR3x class
import com.acs.audiojack.AudioJackReader;
import android.media.AudioManager;
import sk.tido.util.ByteHex;
import java.util.Date;
/**
* This class allows control of the ACR35 reader sleep state and PICC commands
*/
public class Acr3x {
private Acr3xTransmitter transmitter;
private AudioManager mAudioManager;
private AudioJackReader mReader;
private boolean firstReset = true; /** Is this the first reset of the reader? */
/** APDU command for reading a card's UID */
private final byte[] apdu = { (byte) 0xFF, (byte) 0xCA, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
/** Timeout for APDU response (in <b>seconds</b>) */
private final int timeout = 1;
private int acr3xCardType = AudioJackReader.PICC_CARD_TYPE_ISO14443_TYPE_A
| AudioJackReader.PICC_CARD_TYPE_ISO14443_TYPE_B
| AudioJackReader.PICC_CARD_TYPE_FELICA_212KBPS
| AudioJackReader.PICC_CARD_TYPE_FELICA_424KBPS
| AudioJackReader.PICC_CARD_TYPE_AUTO_RATS;
private int acr3xStartAudioLevel = 0;
private Object locking = new Object();
private String lastUuid = "";
private Date lastUuidDate = new Date();
public Acr3x(AudioManager mAudioManager){
this.mAudioManager = mAudioManager;
}
public void start(final Acr3xNotifListener listener){
Runnable r = new Runnable(){
#Override
public void run() {
if(mReader == null){
mReader = new AudioJackReader(mAudioManager);
}
System.out.println("ACR35 reader start");
acr3xStartAudioLevel = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
System.out.println("acr3x start audio stream level: " + acr3xStartAudioLevel);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
System.out.println("acr3x set audio stream level: " + mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
mReader.start();
mReader.setSleepTimeout(30);
mReader.setOnFirmwareVersionAvailableListener(new AudioJackReader.OnFirmwareVersionAvailableListener() {
#Override
public void onFirmwareVersionAvailable(AudioJackReader reader,
String firmwareVersion) {
System.out.println("acr3x firmware version: " + firmwareVersion);
if(listener != null){
listener.onFirmwareVersionAvailable(firmwareVersion);
}
Acr3x.this.read(listener);
}
});
mReader.reset(new AudioJackReader.OnResetCompleteListener(){
#Override
public void onResetComplete(AudioJackReader arg0) {
mReader.getFirmwareVersion();
}
});
}
};
Thread t = new Thread(r, "Acr3xInitThread");
t.start();
}
/**
* Sets the ACR35 reader to continuously poll for the presence of a card. If a card is found,
* the UID will be returned to the Apache Cordova application
*
* #param callbackContext: the callback context provided by Cordova
* #param cardType: the integer representing card type
*/
public void read(final Acr3xNotifListener callbackContext){
System.out.println("acr3x setting up for reading...");
firstReset = true;
/* Set the PICC response APDU callback */
mReader.setOnPiccResponseApduAvailableListener
(new AudioJackReader.OnPiccResponseApduAvailableListener() {
#Override
public void onPiccResponseApduAvailable(AudioJackReader reader,
byte[] responseApdu) {
/* Update the connection status of the transmitter */
transmitter.updateStatus(true);
/* Print out the UID */
String uuid = ByteHex.bytesToHex(responseApdu);
if(uuid.equalsIgnoreCase("0x9000")){
return;
}
if(uuid.endsWith("9000")){
uuid = uuid.substring(0, uuid.length() - 4);
}
if(uuid.equals(lastUuid)){ // na odfiltrovanie opakujucich sa uuid z citacky z predchadzajuceho citania
if(new Date().getTime() - lastUuidDate.getTime() < 3000){
return;
}
}
lastUuid = uuid;
lastUuidDate = new Date();
synchronized(locking){
System.out.println("acr3x uuid: " + uuid);
if(callbackContext != null){
callbackContext.onUUIDAavailable(uuid);
}
System.out.println("acr3x restarting reader");
transmitter.kill();
try {
locking.wait(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
read(callbackContext);
}
});
/* Set the reset complete callback */
mReader.setOnResetCompleteListener(new AudioJackReader.OnResetCompleteListener() {
#Override
public void onResetComplete(AudioJackReader reader) {
System.out.println("acr3x reset complete");
/* If this is the first reset, the ACR35 reader must be turned off and back on again
to work reliably... */
Thread t = null;
if(firstReset){ //firstReset
t = new Thread(new Runnable() {
public void run() {
try{
/* Set the reader asleep */
mReader.sleep();
/* Wait one second */
Thread.sleep(500);
/* Reset the reader */
mReader.reset();
firstReset = false;
} catch (InterruptedException e) {
e.printStackTrace();
// TODO: add exception handling
}
}
});
} else {
/* Create a new transmitter for the UID read command */
transmitter = new Acr3xTransmitter(mReader, mAudioManager, timeout,
apdu, acr3xCardType, locking);
t = new Thread(transmitter);
}
t.start();
}
});
mReader.start();
mReader.reset();
System.out.println("acr3x setup complete");
}
public void stop(){
if(transmitter != null){
transmitter.kill();
}
System.out.println("acr3x restoring audio level: " + acr3xStartAudioLevel);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,acr3xStartAudioLevel, 0);
System.out.println("acr3x set audio stream level: " + mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
if(mReader != null){
mReader.stop();
}
}
}
Transmitter class
import com.acs.audiojack.AudioJackReader;
import android.media.AudioManager;
/**
* This class sets up an independent thread for card polling, and is linked to the
* <code>setOnPiccResponseApduAvailableListener</code> callback function
*/
public class Acr3xTransmitter implements Runnable {
private AudioJackReader mReader;
private AudioManager mAudioManager;
//private CallbackContext mContext;
private boolean killMe = false; /** Stop the polling thread? */
private int itersWithoutResponse = 0; /** The number of iterations that have passed with no
response from the reader */
private boolean readerConnected = true; /** Is the reader currently connected? */
private int cardType;
private int timeout;
private byte[] apdu;
private Object locking;
/**
* #param mReader: AudioJack reader service
* #param mAudioManager: system audio service
* #param mContext: context for plugin results
* #param timeout: time in <b>seconds</b> to wait for commands to complete
* #param apdu: byte array containing the command to be sent
* #param cardType: the integer representing card type
*/
public Acr3xTransmitter(AudioJackReader mReader, AudioManager mAudioManager,
int timeout, byte[] apdu, int cardType, Object locking){
this.mReader = mReader;
this.mAudioManager = mAudioManager;
this.timeout = timeout;
this.apdu = apdu;
this.cardType = cardType;
this.locking = locking;
}
/**
* Stops the polling thread
*/
public void kill(){
killMe = true;
}
/**
* Updates the connection status of the reader (links to APDU response callback)
*/
public void updateStatus(boolean status){
readerConnected = status;
}
/**
* Sends the APDU command for reading a card UID every second
*/
#Override
public void run() {
try {
/* Wait one second for stability */
Thread.sleep(1000);
while (!killMe) {
synchronized(locking){
if(killMe){
continue;
}
/* If the reader is not connected, increment no. of iterations without response */
if(!readerConnected){
itersWithoutResponse++;
}
/* Else, reset the number of iterations without a response */
else{
itersWithoutResponse = 0;
}
/* Reset the connection state */
readerConnected = false;
if(itersWithoutResponse == 4) {
/* Communicate to the Cordova application that the reader is disconnected */
System.out.println("acr3x disconnected");
/* Kill this thread */
kill();
} else if(!mAudioManager.isWiredHeadsetOn()) {
System.out.println("acr3x not connected");
/* Kill this thread */
kill();
} else{
System.out.println("acr3x reading...");
/* Power on the PICC */
mReader.piccPowerOn(timeout, cardType);
/* Transmit the APDU */
mReader.piccTransmit(timeout, apdu);
}
}
/* Repeat every second */
Thread.sleep(1000);
}
/* Power off the PICC */
mReader.piccPowerOff();
/* Set the reader asleep */
mReader.sleep();
/* Stop the reader service */
mReader.stop();
synchronized(locking){
locking.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
// TODO: add exception handling
}
}
}
listener interface:
public interface Acr3xNotifListener {
public void onUUIDAavailable(String uuid);
public void onFirmwareVersionAvailable(String firmwareVersion);
}
First you call the Reset command to activate the device. As the device will fall asleep (after 4 seconds by default)* the trick is to keeping it alive.
You can achieve that by relaunching a new PowerOn command every time the previous PowerOn timedOut. Something like that
void powerOn () {
if (!mReader.piccPowerOn(mPiccTimeout, mPiccCardType)) {
powerOn();
} else {
askNfcForItsId();
}
Don't forget to call powerOn after you read the nfc otherwise it will fall asleep after the 1st nfc card.
*the reset timeout can be set between 4 and 20 seconds

Unable to read data from USB hid device with android in host mode

I'am able to connect to device and ask device specifications:
specs:
Model: /dev/bus/usb/001/002
ID: 1002
Class: 0
Protocol: 0
Vendor ID 1155
Product ID: 22352
Interface count: 1
---------------------------------------
***** *****
Interface index: 0
Interface ID: 0
Inteface class: 3 USB_CLASS_HID
Interface protocol: 0
Endpoint count: 2
++++ ++++ ++++
Endpoint index: 0
Attributes: 3
Direction: 128 (device to host)
Number: 1
Interval: 1
Packet size: 64
Type: 3 USB_ENDPOINT_XFER_INT (interrupt endpoint)
++++ ++++ ++++
Endpoint index: 1
Attributes: 3
Direction: 0 (host to device)
Number: 1
Interval: 1
Packet size: 64
Type: 3 USB_ENDPOINT_XFER_INT (interrupt endpoint)
No more devices connected.
I'am also able to send data from host to device, using this method:
int bufferDataLength = mEndpointOut.getMaxPacketSize();
ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
UsbRequest request = new UsbRequest();
buffer.put(DataToSend);
request.initialize(mDeviceConnection, mEndpointOut);
request.queue(buffer, bufferDataLength);
try
{
if (request.equals(mDeviceConnection.requestWait()))
{
// Read an analyze the incoming data here
byte[] byteBuffer = new byte[buffer.remaining()];
buffer.get(byteBuffer, 0, buffer.remaining());
return true;
}
}
catch (Exception ex)
{
Log.e(TAG, "Error sending data: " + ex.toString());
}
return false;
But i'am not able to read from device, i've tested several methods without success..
for example this doesn't work:
int bufferDataLength = mEndpointIn.getMaxPacketSize();
ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
//Make a request
UsbRequest request = new UsbRequest();
request.initialize(mDeviceConnection, mEndpointIn);
ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength);
//For IN endpoints, data is read into the buffer
request.queue(buffer, bufferDataLength);
//This blocks until the request is successful
//Make sure the request that finished is the one you need
if (mDeviceConnection.requestWait() == request) {
// Read an analyze the incoming data here
byte[] byteBuffer = new byte[buffer.remaining()];
buffer.get(byteBuffer, 0, buffer.remaining());
}
Suggestions?
I resolved my problems using this class, i'm answering to my my question hoping it can help someone else:
/**
* This class is used for talking to hid of the dongle, connecting, disconnencting and enumerating the devices.
* #author gai
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class HidBridge {
private Context _context;
private int _productId;
private int _vendorId;
//private HidBridgeLogSupporter _logSupporter = new HidBridgeLogSupporter();
private static final String ACTION_USB_PERMISSION =
"com.example.company.app.testhid.USB_PERMISSION";
// Locker object that is responsible for locking read/write thread.
private final Object _locker = new Object();
private Thread _readingThread = null;
private boolean _runReadingThread = false;
private String _deviceName;
private UsbManager _usbManager;
private UsbDevice _usbDevice;
// The queue that contains the read data.
private Queue<byte[]> _receivedQueue;
/**
* Creates a hid bridge to the dongle. Should be created once.
* #param context is the UI context of Android.
* #param productId of the device.
* #param vendorId of the device.
*/
public HidBridge(Context context, int productId, int vendorId) {
_context = context;
_productId = productId;
_vendorId = vendorId;
_receivedQueue = new LinkedList<byte[]>();
}
/**
* Searches for the device and opens it if successful
* #return true, if connection was successful
*/
public boolean OpenDevice() {
_usbManager = (UsbManager) _context.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = _usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
_usbDevice = null;
// Iterate all the available devices and find ours.
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
if (device.getProductId() == _productId && device.getVendorId() == _vendorId) {
_usbDevice = device;
_deviceName = _usbDevice.getDeviceName();
}
}
if (_usbDevice == null) {
Log("Cannot find the device. Did you forgot to plug it?");
Log(String.format("\t I search for VendorId: %s and ProductId: %s", _vendorId, _productId));
return false;
}
// Create and intent and request a permission.
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(_context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
_context.registerReceiver(mUsbReceiver, filter);
_usbManager.requestPermission(_usbDevice, mPermissionIntent);
Log("Found the device");
return true;
}
/**
* Closes the reading thread of the device.
*/
public void CloseTheDevice() {
try
{
StopReadingThread();
_context.unregisterReceiver(mUsbReceiver);
}
catch(RuntimeException e)
{
Log("Error happend while closing device. Usb reciver not connected.");
}
}
/**
* Starts the thread that continuously reads the data from the device.
* Should be called in order to be able to talk with the device.
*/
public void StartReadingThread() {
if (_readingThread == null) {
_runReadingThread = true;
_readingThread = new Thread(readerReceiver);
_readingThread.start();
} else {
Log("Reading thread already started");
}
}
/**
* Stops the thread that continuously reads the data from the device.
* If it is stopped - talking to the device would be impossible.
*/
public void StopReadingThread() {
if (_readingThread != null) {
// Just kill the thread. It is better to do that fast if we need that asap.
_runReadingThread = false;
_readingThread = null;
} else {
Log("No reading thread to stop");
}
}
/**
* Write data to the usb hid. Data is written as-is, so calling method is responsible for adding header data.
* #param bytes is the data to be written.
* #return true if succeed.
*/
public boolean WriteData(byte[] bytes) {
try
{
// Lock that is common for read/write methods.
synchronized (_locker) {
UsbInterface writeIntf = _usbDevice.getInterface(0);
UsbEndpoint writeEp = writeIntf.getEndpoint(1);
UsbDeviceConnection writeConnection = _usbManager.openDevice(_usbDevice);
// Lock the usb interface.
writeConnection.claimInterface(writeIntf, true);
// Write the data as a bulk transfer with defined data length.
int r = writeConnection.bulkTransfer(writeEp, bytes, bytes.length, 0);
if (r != -1) {
Log(String.format("Written %s bytes to the dongle. Data written: %s", r, composeString(bytes)));
} else {
Log("Error happened while writing data. No ACK");
}
// Release the usb interface.
writeConnection.releaseInterface(writeIntf);
writeConnection.close();
}
} catch(NullPointerException e)
{
Log("Error happend while writing. Could not connect to the device or interface is busy?");
Log.e("HidBridge", Log.getStackTraceString(e));
return false;
}
return true;
}
/**
* #return true if there are any data in the queue to be read.
*/
public boolean IsThereAnyReceivedData() {
synchronized(_locker) {
return !_receivedQueue.isEmpty();
}
}
/**
* Queue the data from the read queue.
* #return queued data.
*/
public byte[] GetReceivedDataFromQueue() {
synchronized(_locker) {
return _receivedQueue.poll();
}
}
// The thread that continuously receives data from the dongle and put it to the queue.
private Runnable readerReceiver = new Runnable() {
public void run() {
if (_usbDevice == null) {
Log("No device to read from");
return;
}
UsbEndpoint readEp;
UsbDeviceConnection readConnection = null;
UsbInterface readIntf = null;
boolean readerStartedMsgWasShown = false;
// We will continuously ask for the data from the device and store it in the queue.
while (_runReadingThread) {
// Lock that is common for read/write methods.
synchronized (_locker) {
try
{
if (_usbDevice == null) {
OpenDevice();
Log("No device. Recheking in 10 sec...");
Sleep(10000);
continue;
}
readIntf = _usbDevice.getInterface(0);
readEp = readIntf.getEndpoint(0);
if (!_usbManager.getDeviceList().containsKey(_deviceName)) {
Log("Failed to connect to the device. Retrying to acquire it.");
OpenDevice();
if (!_usbManager.getDeviceList().containsKey(_deviceName)) {
Log("No device. Recheking in 10 sec...");
Sleep(10000);
continue;
}
}
try
{
readConnection = _usbManager.openDevice(_usbDevice);
if (readConnection == null) {
Log("Cannot start reader because the user didn't gave me permissions or the device is not present. Retrying in 2 sec...");
Sleep(2000);
continue;
}
// Claim and lock the interface in the android system.
readConnection.claimInterface(readIntf, true);
}
catch (SecurityException e) {
Log("Cannot start reader because the user didn't gave me permissions. Retrying in 2 sec...");
Sleep(2000);
continue;
}
// Show the reader started message once.
if (!readerStartedMsgWasShown) {
Log("!!! Reader was started !!!");
readerStartedMsgWasShown = true;
}
// Read the data as a bulk transfer with the size = MaxPacketSize
int packetSize = readEp.getMaxPacketSize();
byte[] bytes = new byte[packetSize];
int r = readConnection.bulkTransfer(readEp, bytes, packetSize, 50);
if (r >= 0) {
byte[] trancatedBytes = new byte[r - 1]; // Truncate bytes in the honor of r
int i=0;
for (byte b : bytes) {
if (i > 0)
trancatedBytes[i - 1] = b;
i++;
}
_receivedQueue.add(trancatedBytes); // Store received data
Log(String.format("Message received of lengths %s and content: %s", r, composeString(bytes)));
}
// Release the interface lock.
readConnection.releaseInterface(readIntf);
readConnection.close();
}
catch (NullPointerException e) {
Log("Error happened while reading. No device or the connection is busy");
Log.e("HidBridge", Log.getStackTraceString(e));
}
catch (ThreadDeath e) {
if (readConnection != null) {
readConnection.releaseInterface(readIntf);
readConnection.close();
}
throw e;
}
}
// Sleep for 10 ms to pause, so other thread can write data or anything.
// As both read and write data methods lock each other - they cannot be run in parallel.
// Looks like Android is not so smart in planning the threads, so we need to give it a small time
// to switch the thread context.
Sleep(10);
}
}
};
private void Sleep(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
}
}
else {
Log.d("TAG", "permission denied for the device " + device);
}
}
}
}
};
/**
* Logs the message from HidBridge.
* #param message to log.
*/
private void Log(String message) {
//LogHandler logHandler = LogHandler.getInstance();
//logHandler.WriteMessage("HidBridge: " + message, LogHandler.GetNormalColor());
Log.i("HidBridge: ", message);
}
/**
* Composes a string from byte array.
*/
private String composeString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b: bytes) {
builder.append(b);
builder.append(" ");
}
return builder.toString();
}
}

how to know which online databases are available to connect

I'm building a client server android app that has to do with stores and I want (when the user is close to 2 or 3 stores with their database online) my app to understand that he can connect to one of these stores' databases and list them to the screen. (just what is happenning with the available wifis when we want to connect to the internet)
How can I achieve that?
I hope I made clear what I'm looking for.
Correct me if I'm wrong. You are writing an app, that can access data from a server, where the server/database belongs to a store?
If my understanding of your question is correct, do the following:
Create a connection broadcast that listens for changes in connectivity
Create a GPS Manager that compares the current location to that based off the location from the stores
If in range of one or more stores AND a connection is available, query the server via a restfull request, on the server side, fire a query, see if you get any result(I don't know if there exists a specific query to check for database connectivity from server-side code to database) If you get a result, the database is available, send a result back from the server to the client, and list the database/store as available.
I personally would use JSON for the requests from client <-> server. As it is lightweight and easy to use.
For writing a broadcaster: BraodcastReciever
Example:
private Context _context;
private State _state;
private boolean _listening;
private String _reason;
private boolean _isFailOver;
private NetworkInfo _networkInfo;
private NetworkInfo _otherNetworkInfo;
private ConnectivityBroadcastReceiver _receiver;
/**
* The broadcast that listens to connectivity changes(wifi, mobile network etc)
* */
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
/**
* Called when connectivity state changes
*
* #param Context the context
* #param Intent the intent containing the information about the change
* */
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || _listening == false) {
Log.w(TAG, "onReceived() called with " + _state.toString() + " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
//Set the state according to current connectivity.
if(noConnectivity) {
_state = State.NOT_CONNECTED;
} else {
_state = State.CONNECTED;
}
//If current state is CONNECTED. Start background services, otherwise stop services.
switch(_state) {
case CONNECTED:
//Do stuff when connected
break;
case NOT_CONNECTED:
//Do stuff if not connected
break;
}
_networkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
_otherNetworkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
_reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
_isFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.d(TAG, "onRecieve(): _networkInfo= " + _networkInfo + " _otherNetworkInfo= " + (_otherNetworkInfo == null ? "[none]" : _otherNetworkInfo +
" noConn= " + noConnectivity) + " _state= " + _state.toString());
}
};
I am not posting the entire code. I wrote a wrapper around the ConnectivityBroadcastReceiver. But with the given code you should be able to get far enough.Note that in the code State is an enum containing 3 values: CONNECTED, NOT_CONNECTED, UNKNOWN
As for the GPS manager:
/**
* <h1>GPSManager</h1>
*
* <p>
* Manager for GPS tracking.
* Able to enable and disable GPS tracking for the application.
* </p>
* */
public class GPSManager {
public static final String TAG = "LocationFinder";
private double _lat;
private double _lon;
private float _accuracy;
private Context _context;
private LocationManager _locManager;
private LocationListener _locListener;
private static GPSManager _instance;
/**
* Constructor.
*
* #param context The context of the caller.
* */
private GPSManager(Context context) {
this._context = context;
this._locListener = new LocationTracker();
}
/**
* GPSManager is singleton. Retrieve the shared instance.
*
* #param context The context of the caller.
* #return GPSManager An instance of the GPSManager class.
* */
public static synchronized GPSManager getInstance(Context context) {
if(_instance == null) {
_instance = new GPSManager(context);
}
return _instance;
}
/**
* Start tracking GPS locations.
* */
public void startGpsTracking() {
_locManager = (LocationManager)_context.getSystemService(Context.LOCATION_SERVICE);
_locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, _locListener);
}
/**
* Stop tracking GPS locations.
* */
public void stopGpsTracking() {
_locManager.removeUpdates(_locListener);
_locManager = null;
}
/**
* Retrieve the latitude from the GPSManager.
*
* #return double The latitude.
* */
public double getLatitude() {
return _lat;
}
/**
* Retrieve the longitude from the GPSManager.
*
* #return double The longitude.
* */
public double getLongitude() {
return _lon;
}
/**
* Check if the GPSManager has a fix on a location.
*
* #return boolean True if GPSManager has a fix, otherwise false.
* */
public boolean hasFix() {
if(_lat != 0 && _lon != 0)
return true;
else
return false;
}
/**
* Retrieve the accuracy of the fix.
*
* #return float The accuracy.
* */
public float getAccuracy() {
return _accuracy;
}
/**
* Retrieve the last known location.
*
* #return Location The last known location.
* */
public Location getLastLocation() {
return _locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
/**
* <h1>LocationTracker</h1>
*
* <p>Tracks the location for the GPSManager.</p>
* */
private class LocationTracker implements LocationListener {
/** (non-Javadoc)
* #see android.location.LocationListener#onLocationChanged(android.location.Location)
*/
#Override
public void onLocationChanged(Location location) {
_lat = location.getLatitude();
_lon = location.getLongitude();
_accuracy = location.getAccuracy();
}
/** (non-Javadoc)
* #see android.location.LocationListener#onProviderDisabled(java.lang.String)
*/
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Gps Disabled");
}
/** (non-Javadoc)
* #see android.location.LocationListener#onProviderEnabled(java.lang.String)
*/
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Gps Enabled");
}
/** (non-Javadoc)
* #see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {};
};
}
Expand this with your own needs. Most code in the gps manager is self explanatory.
And for the restfull stuff, theres so many different approaches, you will have to look that up yourself.
As answer to your comment, I will show you my implementation of the webrequest.
I personally use apache-mime4j-0.6.jar AND httpmime-4.0.1.jar.
WebService _service = new WebService();
#Override
protected String doInBackground(String... arg0) {
try {
MultipartEntity multipart = new MultipartEntity();
multipart.addPart("username", new StringBody(_inputName));
multipart.addPart("password", new StringBody(_inputPass));
_service.post(QfConfig.RESTFUL_LOGIN_URL, multipart);
long response = _service.getLongResponse();
if(response != 0) {
_pgUserId = response;
_onlineValidated = true;
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
I don't know wether you want to POST or GET. The above example uses POST.
I create a MultipartEntity, and add 2 parts to it. The multipart will be send across to the server as a form where the name of the POST value is username, and the VALUE of the post where the name is username is new StringBody(_inputName).
For the post section in my WebService class:
public void post(String url, MultipartEntity postData) {
HttpClient client = null;
HttpPost post = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
InputStream _inStream = null;
try {
client = new DefaultHttpClient();
post = new HttpPost();
URI uri = URI.create(url);
post.setURI(uri);
post.setEntity(postData);
//Execute the HttpPost request and store the response in httpResponse.
httpResponse = client.execute(post);
//Set the response code from the request's responst.
setResponseCode(httpResponse.getStatusLine().getStatusCode());
//Retrieve the entity from the response.
entity = httpResponse.getEntity();
if(entity != null) {
//Retrieve the content from the entity.
_inStream = entity.getContent();
//Convert the InputStream to String and set the String response to the returned value.
setStringResponse(IOUtility.convertStreamToString(_inStream));
//Close the InputStream.
Log.d(TAG, getStringResponse());
}
//try to create a numeric value of the response result and store it if so
if(GeneralUtil.isNumeric(getStringResponse())) {
setLongResponse(Long.parseLong(getStringResponse()));
}
Log.d(TAG, httpResponse.getStatusLine().getReasonPhrase());
} catch(Exception e) {
e.printStackTrace();
setResponseCode(0);
setLongResponse(0);
setStringResponse("");
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
I work via https, which is more complex so I left those things out. What I do here is, create a new httpClient and HttpPost, set the URI if the post, add the multipart data to post.setEntity() and then execute the request and save the response in a HttpResponse object.
I then retrieve the entity and save it as HttpEntity, as to where I get the response content out of. Which can be a JSON string, a number, whatever you want basically.
I then set some methods which helps me retrieve the results easily by getters and setters.
For a HttpGet its even easier, you only need to pass an url , instead of a HttpPost object you create an HttpGet object, pass it the url, _client.execute([HttpGet object]) and retrieve the result the same way.
In the php script, you can literally just use $_POST['username'] which would give the value of username that u set in StringBody in the above code.
With a get, I would advise sending an url(with or without params, and then send back a JSON string as result to the get request.
Let me know if you need more help. I think this is as far as I can go though. I can't show the php side cause I use a self designed framework.

Categories

Resources