I want to create a simple app which is intend to call a API in POST method when a button clicks.The app workflow will be like this; user enter the url and a timeout value, and press start button. The API will called in the provided url and it will again and again call according to the timeout value provided. When user press the stop button,all activity should stop.The API call will not provide any data in response. I simply want to call that API in POST method.In order to achieve this I written the API call in a service.
The problem Iam facing is
The POST method doesn't working.
2.How can I call this api in background according to the timeout value provided.?
What I have Done
My MainActivity
url = (EditText)findViewById(R.id.editText3);
timeOut = (EditText)findViewById(R.id.editText5);
Button clickButton = (Button) findViewById(R.id.start);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, APIService.class);
Bundle bund = new Bundle();
bund.putString("url",url.getText().toString());
bund.putString("timeout",timeOut.getText().toString());
intent.putExtras(bund);
startService(intent);
}
});
Button stopbutton = (Button) findViewById(R.id.stop);
stopbutton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, APIService.class);
stopService(intent);
}
});
My API Service class
public APIService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, " Client API Service Started", Toast.LENGTH_LONG).show();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Client API Service Started", Toast.LENGTH_LONG).show();
String WEBURL;
String TimeOut;
Bundle bund = intent.getExtras();
WEBURL=bund.getString("url");
TimeOut=bund.getString("timeout");
String URL= "http://"+WEBURL+"/API/ReportSubscription/GetAllReportSubscription?subscriptionUR="+WEBURL;
new HttpRequestTask(
new HttpRequest(URL, HttpRequest.POST),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Client API Service Stopped", Toast.LENGTH_LONG).show();
}
}
I Used compile 'com.apptakk.http_request:http-request:0.1.2' for Web API call.Any help is appriciated
You can use OkHttp for this. See this tutorial for more: https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html
// avoid creating several instances, should be singleon
OkHttpClient client = new OkHttpClient();
String weburl = bund.getString("url");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("subscriptionUR", weburl)
.build();
Request request = new Request.Builder()
.url("http://"+weburl+"/API/ReportSubscription/GetAllReportSubscription")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Do something when request failed
e.printStackTrace();
Log.d(TAG, "Request Failed.");
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()){
throw new IOException("Error : " + response);
}else {
Log.d(TAG,"Request Successful.");
}
// Read data in the worker thread
final String data = response.body().string();
}
});
First make sure your API is working by testing through Postman. After you have make sure that API is working fine from the backend itself then the problem is from your mobile side calling that API. I would really recommend retrofit (https://square.github.io/retrofit/) to try out API calling task asynchronously because its really easy and standard way .You simply using POST method in api by passing your time out value as a parameter and your api url as base url.
You can use service in android to execute in the background i.e your API calling
Related
Ok, I have no Idea how to do this, I need some help.
I need to send a Ping in JSON format into a server, I've already have it with all the information that I need... timestamp, location, device_id, etc... But.. how can I send it each 5 minutes automatically ?? I'm still looking for something useful but I have no succes.. I'm kind of new on this..
here's an example of my code, feel free to use it if it is useful for you :) ...
package com.example.hugo.ping03;
// imports....
public class MainActivity extends ActionBarActivity {
//HTTP
private AsyncHttpClient client;//crear cliente
private AsyncHttpResponseHandler handler;//crear handler
private Button send;
//JSON
JSONObject json; //objeto json
Context context = this; //context element
private StringEntity entity; //entity
//Battery
private IntentFilter batIntentFilter;
private Intent battery;
private int nivelBateria;
//device_id
private String id;
//timestamp
private int time;
private Timestamp tsTemp;
private Long tsLong;
private String ts;
//GPS (this one comes from another class.java)
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping03);
client = new AsyncHttpClient();
String password = "pass";
client.setBasicAuth("hugo", password);
send = (Button) findViewById(R.id.send);
//battery level:
batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
battery = this.registerReceiver(null, batIntentFilter);
nivelBateria = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//device_id:
id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
//timestamp
time = (int) (System.currentTimeMillis());
tsTemp = new Timestamp(time);
tsLong = System.currentTimeMillis()/1000;
ts = tsLong.toString();
handler = new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
Log.d("onSuccess","ping exitoso !!!!");
Log.d("Nivel de Bateria:",String.valueOf(nivelBateria));
Log.d("Id de Dispositivo",id);
Log.d("Timesatmp:",ts);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
String statuscode = String.valueOf(statusCode);
Log.d("onFailure","ping nulo a causa de: ");
Log.d("Server statusCode",statuscode);
}
};
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mensaje a Log para indicar clic en botón
Log.d("onPressButton","Click exitoso");
String klientourl = "server url";
//Strings to Post JSON :
String status = "1";
String device_id = id;
String timestamp =ts;
String battery = String.valueOf(nivelBateria);
json = new JSONObject();
gps = new GPSTracker(Ping03.this);//creamos objeto de clase
//if GPS is Enabled...
if (gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.d("Location is:", "Lat: "+latitude+" Long: "+longitude);
String IamHere = "Lat: "+latitude+" Long: "+longitude;
try {
json.put("geo", IamHere);
json.put("status", status);
json.put("device_id", device_id);
json.put("timeStamp", timestamp);
json.put("battery", battery);
}catch (JSONException e){
Log.e("Json", "unexpected JSON exception", e);
}
try {
entity = new StringEntity(json.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(context, klientourl, entity, "application/json", handler);
}catch (Exception e){}
}else {
//if we can
gps.showSettingsAlert();
Log.d("Geoloc: ", "Disabled?");
}
}// ./ end onClick
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_ping03, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
Any ideas? thanks a lot!
If you want to perform some periodically repeating tasks, I'd suggest you make use of a AlarmManager component of the Android SDK.Alarm manager is a system service, thus you can access it by using the following line of code.
AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().
You will then receive the alarm in an AlarmReceiver.
AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone.
Here is an article from Android Developers that describes how to use AlarmManager and AlarmReceiver : http://developer.android.com/training/scheduling/alarms.html. After you are successful of setting an alarm with AlarmManager (for every 5 minutes) and intercepting it in your AlarmReceiver, you can start an IntentService that will send the ping json to your server.
I hope this helps. Cheers!
If you want to hit you server from android app after a fix time you should create a background service.and this service class will call server on a specific delay frequently.
public class MyService extends Service{
Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0){
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate(){
Log.e(TAG, "onCreate");
mHandler.postDelayed(mRun,300000);
}
Runnable mRun = new Runnable() {
#Override
public void run() {
// TODO call your service here
mHandler.postDelayed(mRun,300000);
}
};
}
start service from your activity like below -
private void startService(){
Handler mStartServicehandler = new Handler();
mStartServicehandler.post(new Runnable() {
#Override
public void run() {
startService(new Intent(mContext,MyService.class));
}
});
}
do something like this.
It will ping your server after every 5 min.
When I get UserRecoverableAuthIOException in AbstractThreadedSyncAdapter, I'm creating a notification as below.
Here's how I'm creating the service:
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i("Service", "Thread started");
return this.getSyncAdapter().getSyncAdapterBinder();
}
private GoogleTasksSyncAdapter getSyncAdapter() {
if (syncAdapter == null)
{
Log.i("Service", "syncAdapter started");
syncAdapter = new MySyncAdapter(this);
}
return syncAdapter;
}
Once the thread is started, I'm raising a notification. But once user clicks on the notification, they can see the authorization activity. After authorising how to resume from the last point. I.e how to get notified once the activity is closed in Syncadapter.
The SyncAdapter thread are running, and you want to get notification when SyncAdapter ends, right?
So, you can comunicate the SyncAdapter thread with BroadCast.
In your SyncAdapter class:
Intent i = new Intent(SYNC_FINISHED);
context.sendBroadcast(i);
Log.i(TAG, "Network synchronization complete");
In a activity or a fragment:
private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Sync finished!!");
// Here you can send your notification or another thing that you want
}
};
#Override
public void onStart() {
super.onStart();
getActivity().registerReceiver(syncFinishedReceiver, new IntentFilter(SyncAdapter.SYNC_TASK_FINISHED));
}
#Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(syncFinishedReceiver);
}
NOTE: The SYNC_FINISHED constant, you can define previously in your SyncAdapter
I hope I've helped you.
Greetings!
In your SyncAdapter you do something like:
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.i(TAG, "Beginning network synchronization");
if(extras.getBoolean(RUN_METHOD_1) || extras.getBoolean(RUN_ALL)) {
method1();
}
if(extras.getBoolean(RUN_METHOD_2) || extras.getBoolean(RUN_ALL)) {
method2();
}
}
public void method1(){
try{
// do something
} catch (Exception e) {
e.printStackTrace();
// here you can send your notification when exception occours.
}
}
public void method2(){
try{
// do something
} catch (Exception e) {
e.printStackTrace();
// here you can send your notification when exception occours.
}
}
in your "authorization" code you do something like:
Bundle b = new Bundle();
b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
b.putBoolean(SyncAdapter.RUN_METHOD_1, true);
ContentResolver.requestSync(account, CONTENT_AUTHORITY, b);
so you can run where the sync stopped.
Greetings!!!
Here is the solution,
we need to use the syncResult.stats.numAuthExceptions to tell about exception, it throws message automatically. syncResult.delayUntil will wait and restart sync after elapsing time
How to show sync failed message
I want to know how could I setup my application to update its details via API post every after 15 minutes. Right now, I knos how to use get and use a thread in order to create a loader for it while accessing the API.
Here's how I do it:
private int authenticateLogin()
{
EditText user = ((EditText)findViewById(R.id.username));
EditText pass = ((EditText)findViewById(R.id.password));
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String username = user.getText().toString(), password = pass.getText().toString();
String URL = "MyUrl";
String authData = "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Authorization", authData);
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
StatusLine sl = response.getStatusLine();
int statCode = sl.getStatusCode();
if (statCode == 200) {
String entityStringDrivers = EntityUtils.toString(response.getEntity());
Intent i = new Intent(Login.this,DriverLogin.class);
i.putExtra("stringDrivers", entityStringDrivers);
startActivity(i);
return 100;
}
else
{
user.setText("");
pass.setText("");
Toast.makeText(getBaseContext(), "Unauthorized Login", Toast.LENGTH_SHORT).show();
return 100;
}
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
return 100;
}
finally {
}
}
I want to to know how should I do it when posting and do it in background. I don't know where to start specially with the every 15 minutes POST. Any ideas? Thanks!
You can check this out , and use Intent Services to run in the back ground.
android timer, For intent servicse check it out Intent Services
Use a handler for the timer as follows:
In the snippet call startTimeReqTask() to start your timer.
private Handler m_handler = new Handler();
....
Runnable m_handlerTask = new Runnable() {
#Override
public void run() {
m_handler.postDelayed(m_handlerTask, 900000); // 15 minutes
new authenticateLoginTask().execute(); // POST (your asynctask)
}
};
private void startTimeReqTask() // start timer
{
m_handlerTask.run();
}
private void stopTimeReqTask() // stop time
{
m_handler.removeCallbacks(m_handlerTask);
}
And use AsyncTask authenticateLoginTask for doing it background.
If you want to do this background, create a Service and start it in your main activity's onCreate or some BroadcastReceiver
eg:( You need to add try-catch or other sort of protective code)
public class MyService extends Service {
#Override
public void onStartCommand(Intent intent, int flags, int startId) {
//Use intent to pass your username and password here
//start a PostThread here.
}
private class PostThread extends Thread {
private static final int INTERVAL = 15 * 60 * 1000L;
private boolean canceled = false;
#Override
public void run() {
while (!canceled) {
Post();
Thread.sleep(INTERVAL); // or you can use a Timer to trigger this
}
}
public void interrupt() { canceled = true; super.interrupt();}
}
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// call your api method here
}
});
}
}, 0, /*here define your internal*/);
// when you no longer required this api call just call "cancel" method of timer
I got a code from internet for inapp billing and I want to use that code in my application but I am getting an error that when I click the the buy button of my app it redirect me to the another layout of the code where I get an another Button and after that click my in-app billing starts.
I want that when I click my buy button then the in-app billing should start. without any another button clicks.
This is the code from where the the in-app billing start.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSP = PreferenceManager.getDefaultSharedPreferences(this);
Log.i("BillingService", "Starting");
setContentView(R.layout.contact_market);
mContext = this;
mPurchaseButton = (Button) findViewById(R.id.main_purchase_yes);
mPurchaseButton.setOnClickListener(this);
mPreview = (TextView) findViewById(R.id.chakkde);
startService(new Intent(mContext, BillingService.class));
BillingHelper.setCompletedHandler(mTransactionHandler);
}
public Handler mTransactionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Log.i(TAG, "Transaction complete");
Log.i(TAG, "Transaction status: "
+ BillingHelper.latestPurchase.purchaseState);
Log.i(TAG, "Item purchased is: "
+ BillingHelper.latestPurchase.productId);
if (BillingHelper.latestPurchase.isPurchased()) {
showItem();
}
};
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_purchase_yes:
if (BillingHelper.isBillingSupported()) {
BillingHelper.requestPurchase(mContext,
"android.test.purchased");
} else {
Log.i(TAG, "Can't purchase on this device");
mPurchaseButton.setEnabled(false);
}
break;
default:
Log.i(TAG, "default. ID: " + v.getId());
break;
}
}
private void showItem() {
mPreview.setVisibility(View.VISIBLE);
SharedPreferences.Editor prefEditor = mSP.edit();
prefEditor.putBoolean(DroidSugarPreference.KEY_ENABLE,
true);
prefEditor.commit();
startActivity(new Intent(InAppMain.this, Setup.class));
InAppMain.this.finish();
}
#Override
protected void onPause() {
Log.i(TAG, "onPause())");
super.onPause();
}
#Override
protected void onDestroy() {
BillingHelper.stopService();
super.onDestroy();
}
}
this if from where I call the above class
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.gtask_button:
startActivity(new Intent(getActivity(), InAppMain.class));
default:
break;
}
but now i want that from case R.id.gtask_button: i should start the in-app billing activity that i was starting from R.id.main_purchase_yes.
thnx in advance...
From what i see, this is called when you click the button
BillingHelper.requestPurchase(mContext, "android.test.purchased");
So maybe thats where it changes your layout to something else...
Post the method so we can take a look.
EDIT:
Ok, here's the code
protected static void requestPurchase(Context activityContext, String itemId){
if (amIDead()) {
return;
}
Log.i(TAG, "requestPurchase()");
Bundle request = makeRequestBundle("REQUEST_PURCHASE");
request.putString("ITEM_ID", itemId);
try {
Bundle response = mService.sendBillingRequest(request);
//The RESPONSE_CODE key provides you with the status of the request
Integer responseCodeIndex = (Integer) response.get("RESPONSE_CODE");
//The PURCHASE_INTENT key provides you with a PendingIntent, which you can use to launch the checkout UI
PendingIntent pendingIntent = (PendingIntent) response.get("PURCHASE_INTENT");
//The REQUEST_ID key provides you with a unique request identifier for the request
Long requestIndentifier = (Long) response.get("REQUEST_ID");
Log.i(TAG, "current request is:" + requestIndentifier);
C.ResponseCode responseCode = C.ResponseCode.valueOf(responseCodeIndex);
Log.i(TAG, "REQUEST_PURCHASE Sync Response code: "+responseCode.toString());
startBuyPageActivity(pendingIntent, new Intent(), activityContext);
} catch (RemoteException e) {
Log.e(TAG, "Failed, internet error maybe", e);
Log.e(TAG, "Billing supported: "+isBillingSupported());
}
}
and we find the culprit -
startBuyPageActivity(pendingIntent, new Intent(), activityContext);
I'm trying to integrate the Twilio client into a larger application. Everything seems to work fine until I call device.connect(parameters, connectionListener). I get the 31100 Generic Malformed Request error and that's it.
On the same device, using the same Twilio account and the same Twilio application, the sample code supplied with the Twilio Android SDK (MonkeyPhone) works perfectly.
I can't find any more details about what the error means or what are the possible causes. While I'm assuming that I'm sending invalid data, I don't see how is that possible. The Capability Token is OK, I've verified it against the one generated in the MonkeyPhone sample app. Creating a Device works fine, no errors. The error is thrown even when I'm not sending any parameters in the connect() method. The onConnecting() method of the ConnectionListener gets called, but then the onDisconnected(Connection inConnection, int inErrorCode, String inErrorMessage) is called with the Malformed Request error.
The code for the Voice TwiML is working fine, it's just a simple PHP script generating the most simple <Dial> verb possible:
<Response>
<Dial>someone</Dial>
</Response>
Other specific information... I'm running another service in my application, used to do various other operations. Could this interfere in some way? Also, I'm using a trial account and I'm living in Romania, where calling real phone numbers is not supported (but I'm not using phone numbers anyway). Could this affect me in any way?
I apologize in advance for throwing the huge wall of code, but I hope a second pair of eyes can spot something wrong. This is the version of the code most similar to the MonkeyPhone sample. The only difference is that I'm using an AsyncTask to get the capability token (the JsonAsyncRequestWithError class.
public class MonkeyPhone implements Twilio.InitListener, DeviceListener {
private static final String TAG = "MonkeyPhone";
private Context context;
private Device device;
private Connection connection;
public MonkeyPhone(Context context) {
this.context = context;
Twilio.initialize(context, this /* Twilio.InitListener */);
}
#Override
/* Twilio.InitListener method */
public void onInitialized() {
Log.d(TAG, "Twilio SDK is ready");
// the Emulator has a somewhat unique "product" name
String clientName = "doug";
HttpGet get = new HttpGet("http://teamphoenix.zzl.org/capability.php?ClientName=" + clientName);
JsonAsyncRequestWithError asyncRequestWithError = new JsonAsyncRequestWithError(context, "test", new AsyncRequestWithErrorListener() {
#Override
public void onResult(AsyncRequestResponse response, Object destination) {
createDevice(response.getMessage());
}
#Override
public void onErrorResult(AsyncRequestResponse response, Object destination) {
}
});
asyncRequestWithError.execute(get);
}
public void createDevice(String token) {
try {
device = Twilio.createDevice(token, this /* DeviceListener */);
Intent intent = new Intent(context, SpringshotPhoneActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} catch (Exception e) {
Log.e(TAG, "", e);
}
}
#Override
/* Twilio.InitListener method */
public void onError(Exception e) {
Log.e(TAG, "Twilio SDK couldn't start: " + e.getLocalizedMessage());
}
#Override
/* DeviceListener method */
public void onStartListening(Device inDevice) {
Log.i(TAG, "Device is now listening for incoming connections");
}
#Override
/* DeviceListener method */
public void onStopListening(Device inDevice) {
Log.i(TAG, "Device is no longer listening for incoming connections");
}
#Override
/* DeviceListener method */
public void onStopListening(Device inDevice, int inErrorCode, String inErrorMessage) {
Log.i(TAG, "Device is no longer listening for incoming connections due to error " + inErrorCode + ": " + inErrorMessage);
}
#Override
/* DeviceListener method */
public boolean receivePresenceEvents(Device inDevice) {
return false; // indicate we don't care about presence events
}
#Override
/* DeviceListener method */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
public void connect(String phoneNumber) {
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("PhoneNumber", phoneNumber);
/// ---------------- THIS IS THE CALL THAT FAILS ------------------------------------//
connection = device.connect(parameters, null /* ConnectionListener */);
if (connection == null)
Log.w(TAG, "Failed to create new connection");
}
public void disconnect() {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
public void handleIncomingConnection(Device inDevice, Connection inConnection) {
Log.i(TAG, "Device received incoming connection");
if (connection != null)
connection.disconnect();
connection = inConnection;
connection.accept();
}
#Override
protected void finalize() {
if (connection != null)
connection.disconnect();
if (device != null)
device.release();
}
}
Thank you very much!
I figured out the problem. Apparently, I had to read the InputStream from the server using the UTF-8 encoding (even if there are no special characters in the token).
char[] buf = new char[1024];
InputStream is = response.getEntity().getContent();
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, "UTF-8");
int bin;
while ((bin = in.read(buf, 0, buf.length)) >= 0) {
out.append(buf, 0, bin);
}
return out.toString();