how to show toast message in asyncTask doingbackground or onPostExecute - android

package kr.phpdev.call;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PhoneStateReceiver extends BroadcastReceiver {
static String mLastState;
static final String TAG = "Call Manager";
final OkHttpClient client = new OkHttpClient();
#Override
public void onReceive(Context context, Intent intent) {
CallReceivedChk(context, intent);
}
private void CallReceivedChk(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String mState = String.valueOf(state);
if (mState.equals(mLastState)) { // 두번 호출되는 문제 해결 목적
return;
} else {
mLastState = mState;
}
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_RINGING >>> " + PhoneNumberUtils.formatNumber(incomingNumber));
RequestBody formBody = new FormBody.Builder()
.add("pn", PhoneNumberUtils.formatNumber(incomingNumber))
.build();
final Request request = new Request.Builder()
.url("http://phpdev.kr/cm/logsend.php")
.post(formBody)
.build();
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
return null;
}
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(getApplicationContext(), "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
};
asyncTask.execute();
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
}
how can i get toast message?

You need to do that on onPostExecute since it is running on the UI thread. And also in Java string comparison is like s.equals("Failed"):
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.equals("FAILED")) {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}

Use Toast.makeText(context, "토스트메시지입니다.",Toast.LENGTH_SHORT).show();`
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}

Error:(103, 68) error: local variable context is accessed from within inner class; needs to be declared final. You just need using "context" instead of "getApplicationContext()".

Related

Sending SMS using code sends duplicate SMS

I just start android with a small project. I am trying to do the following:
STEP 1. get the response from an url [https://client.itscholarbd.com/getsmsdata]
STEP 2. send sms based on the data received from step 1
STEP 3. DELETE the data which is processed. i.e. sms is sent. this is done by DELETE request with ID
STEP 4. REPEAT from STEP 1.
Here is my code:
package com.pkappstudio.smsv20;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BackgroundService extends Service {
private static final String SMS_SENT_ACTION = "com.pkappstudio.smsv20.SMS_SENT";
private static final String EXTRA_NUMBER = "number";
private static final String EXTRA_MESSAGE = "message";
private RequestQueue requestQueue;
private SmsManager smsManager;
private BroadcastReceiver resultsReceiver;
private boolean start = true;
private String base_url = "https://client.itscholarbd.com";
#Override
public void onCreate() {
super.onCreate();
smsManager = SmsManager.getDefault();
resultsReceiver = new SmsResultReceiver();
IntentFilter intentFilter = new IntentFilter(SMS_SENT_ACTION);
registerReceiver(resultsReceiver, intentFilter);
requestQueue = Volley.newRequestQueue(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String macAddress = intent.getStringExtra("MAC");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_ID)
.setContentTitle("SMS v2.0-Service Running")
.setContentText(macAddress)
.setSmallIcon(R.drawable.ic_message)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//our action starts here
if (start) {
jsonParse();
}
handler.postDelayed(this, 8000);
}
}, 8000);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(resultsReceiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void jsonParse() {
String url = base_url+"/getsmsdata?mac=" + App.MAC_ADDRESS;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("response");
getData(array);
Log.i("reposnse", array.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("JSONDATA", error.toString());
}
});
requestQueue.add(request);
}
private void getData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
String string = object.getString("phone");
int id = Integer.parseInt(object.getString("id"));
int user_id = Integer.parseInt(object.getString("user_id"));
String message = object.getString("message");
double smsLength = message.length();
double perSmsLength = 160;
double FakeQuantity = smsLength / perSmsLength;
int quantity = (int) Math.ceil(FakeQuantity);
start = false;
Log.i("debug", message);
sendNextMessage(id, string, message, quantity, user_id);
deleteFromDB(id);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void deleteFromDB(int id) {
String url = base_url+"/deletedata?id=" + id + "&mac=" + App.MAC_ADDRESS;
StringRequest request = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("resonse", response);
jsonParse();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("resonse", error.toString());
}
});
requestQueue.add(request);
}
private void sendStatusToServer(JSONArray array) {
String url = base_url+"/addsmslog?mac=" + App.MAC_ADDRESS;
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, array, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("response", error.toString());
}
});
requestQueue.add(request);
}
private void sendNextMessage(int id, String number, String message, int quantity, int user_id) {
int requestCode = id + Integer.parseInt(number);
Intent sentIntent = new Intent(SMS_SENT_ACTION);
sentIntent.putExtra(EXTRA_NUMBER, number);
sentIntent.putExtra(EXTRA_MESSAGE, message);
sentIntent.putExtra("quantity", quantity);
sentIntent.putExtra("user_id", user_id);
sentIntent.putExtra("id", id);
PendingIntent sentPI = PendingIntent.getBroadcast(this,
requestCode,
sentIntent,
PendingIntent.FLAG_ONE_SHOT);
// Send our message.
Log.i("dValues", id + " " + number + " " + message);
smsManager.sendTextMessage(number, null, message, sentPI, null);
}
private class SmsResultReceiver extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
// Get the result action.
String action = intent.getAction();
// Retrieve the recipient's number and message.
String number = intent.getStringExtra(EXTRA_NUMBER);
String message = intent.getStringExtra(EXTRA_MESSAGE);
int user_id = intent.getIntExtra("user_id", 0);
int quantity = intent.getIntExtra("quantity", 0);
String sent_result;
if (SMS_SENT_ACTION.equals(action)) {
start = true;
int resultCode = getResultCode();
sent_result = translateSentResult(resultCode);
JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
try {
object.put("phone", number);
object.put("message", message);
object.put("quantity", quantity);
object.put("user_id", user_id);
object.put("status", sent_result);
object.put("delivered", null);
} catch (Exception e) {
e.printStackTrace();
}
array.put(object);
sendStatusToServer(array);
Log.i("dResponse", array.toString());
}
}
String translateSentResult(int resultCode) {
switch (resultCode) {
case Activity.RESULT_OK:
return "Sent";
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
return "Failed";
case SmsManager.RESULT_ERROR_RADIO_OFF:
return "Radio off";
case SmsManager.RESULT_ERROR_NULL_PDU:
return "PDU Error";
case SmsManager.RESULT_ERROR_NO_SERVICE:
return "Error Service";
default:
return "Unknown error code";
}
}
}
}
Everything works like a charm. some data is being processed twice. Suppose. at step 1: we got the following json data:
{"response":[{"id":395,"phone":"01620010950","message":"testing! -
itscholarbd.com","user_id":1},{"id":396,"phone":"01673050495","message":"testing! - itscholarbd.com","user_id":1}]}
Then id: 395 is processed twice. I struggle with such problem for 2 days. at last I post here for any idea. Thanks in advance.
I guess that the problem is by calling jsonParse() again in your deleteFromDB(...) method:
private void deleteFromDB(int id) {
.......
.......
#Override
public void onResponse(String response) {
Log.i("resonse", response);
//here, I guess this is the problem
jsonParse();
}
......
......
}

Sending information to ubidots only if the condition are met

The Image shows the dashboard of the application
package com.example.leeyueloong.proximityapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement;
import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory;
import com.estimote.proximity_sdk.proximity.EstimoteCloudCredentials;
import com.estimote.proximity_sdk.proximity.ProximityContext;
import com.estimote.proximity_sdk.proximity.ProximityObserver;
import com.estimote.proximity_sdk.proximity.ProximityObserverBuilder;
import com.estimote.proximity_sdk.proximity.ProximityZone;
import com.ubidots.ApiClient;
import com.ubidots.Variable;
import java.util.ArrayList;
import java.util.List;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
public class MainActivity extends AppCompatActivity {
private ProximityObserver proximityObserver;
private int send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EstimoteCloudCredentials cloudCredentials =
new EstimoteCloudCredentials("tan-kok-hui-s-proximity-fo-07q", "d18623351c273ce3e09ffcc1f6201861");
// 2. Create the Proximity Observer
this.proximityObserver =
new ProximityObserverBuilder(getApplicationContext(), cloudCredentials)
.withOnErrorAction(new Function1<Throwable, Unit>() {
#Override
public Unit invoke(Throwable throwable) {
Log.e("app", "proximity observer error: " + throwable);
return null;
}
})
.withLowLatencyPowerMode()
.build();
// add this below:
ProximityZone zone = this.proximityObserver.zoneBuilder()
.forTag("desks")
.inNearRange()
.withOnEnterAction(new Function1<ProximityContext, Unit>() {
#Override
public Unit invoke(ProximityContext context) {
String deskOwner = context.getAttachments().get("desk-owner");
Log.d("app", "Welcome to " + deskOwner + "'s desk");
return null;
}
})
.withOnExitAction(new Function1<ProximityContext, Unit>() {
#Override
public Unit invoke(ProximityContext context) {
return null;
}
})
.withOnChangeAction(new Function1<List<? extends ProximityContext>, Unit>() {
#Override
public Unit invoke(List<? extends ProximityContext> contexts) {
List<String> deskOwners = new ArrayList<>();
for (ProximityContext context : contexts) {
deskOwners.add(context.getAttachments().get("desk-owner"));
}
for (int i = 0; i < deskOwners.size(); i++) {
if (deskOwners.get(i).contains("Peter")) {
send = 1;
Toast.makeText(MainActivity.this, "Alert:Unauthorized Zone", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Sending information to ubidots..........", Toast.LENGTH_LONG).show();
} else if (deskOwners.get(i).contains("Alex")) {
send = 0;
Toast.makeText(MainActivity.this, "Device has entered this range", Toast.LENGTH_SHORT).show();
}
else if (deskOwners.get(i).contains("Paul"))
{
}
}
Log.d("app", "In range of desks: " + deskOwners);
return null;
}
})
.create();
this.proximityObserver.addProximityZone(zone);
ProximityZone innerZone = this.proximityObserver.zoneBuilder()
.forTag("treasure")
.inCustomRange(3.0)
.create();
ProximityZone outerZone = this.proximityObserver.zoneBuilder()
.forTag("treasure")
.inCustomRange(9.0)
.create();
RequirementsWizardFactory
.createEstimoteRequirementsWizard()
.fulfillRequirements(MainActivity.this,
// onRequirementsFulfilled
new Function0<Unit>() {
#Override
public Unit invoke() {
Log.d("app", "requirements fulfilled");
proximityObserver.start();
return null;
}
},
// onRequirementsMissing
new Function1<List<? extends Requirement>, Unit>() {
#Override
public Unit invoke(List<? extends Requirement> requirements) {
Log.e("app", "requirements missing: " + requirements);
return null;
}
},
// onError
new Function1<Throwable, Unit>() {
#Override
public Unit invoke(Throwable throwable) {
Log.e("app", "requirements error: " + throwable);
return null;
}
});
}
private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (send == 1 || send == 0) {
new ApiUbidots().execute(send);
}
}
};
#Override
protected void onStart() {
super.onStart();
registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
// Stop the BroadcastReceiver
#Override
protected void onStop() {
unregisterReceiver(mBatteryReceiver);
super.onStop();
}
// In Charge of sending variable to ubidots
public class ApiUbidots extends AsyncTask<Integer, Void, Void> {
private final String API_KEY = "A1E-0109ebb46b4990a4ed82f74d2912a9e6b481";
private final String VARIABLE_ID = "5b62ab7ac03f97418ba1c28e";
#Override
protected Void doInBackground(Integer... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable batteryLevel = apiClient.getVariable(VARIABLE_ID);
batteryLevel.saveValue(params[0]);
return null;
}
}
}
The problem is i am able to sending the data to the ubidots however i want to make it so that only if the condition has met, it will then send to the cloud. Other than that, it would not have send any data to the cloud.

My sinch client posts duplicate messages into parse database

My sinch client sends duplicate messages to my parse database in an incremental way. That is for the first message it posts once in the database. Twice for the second message. Thrice for the third in that order.
This is my ChatActivity
package com.app.knowtes;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.messaging.Message;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
import com.sinch.android.rtc.messaging.MessageFailureInfo;
import com.sinch.android.rtc.messaging.WritableMessage;
import java.util.Arrays;
import java.util.List;
/**
* Created by RR on 12/6/2015.
*/
public class ChatActivity extends ActionBarActivity {
private String recipientId;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private String currentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
ListView messagesList;
MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatactivity);
bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
//get recipientId from the intent
Intent intent = getIntent();
recipientId = intent.getStringExtra("RECIPIENT_ID");
currentUserId = ParseUser.getCurrentUser().getObjectId();
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
messagesList = (ListView) findViewById(R.id.listMessages);
messageAdapter = new MessageAdapter(this);
messagesList.setAdapter(messageAdapter);
String[] cuserIds = {currentUserId, recipientId};
String[] ruserIds = {recipientId,currentUserId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(cuserIds));
query.whereContainedIn("recipientId", Arrays.asList(ruserIds));
query.orderByAscending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < messageList.size(); i++) {
WritableMessage message = new WritableMessage(messageList.get(i).get("recipientId").toString(), messageList.get(i).get("messageText").toString());
if (messageList.get(i).get("senderId").toString().equals(currentUserId)) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_OUTGOING);
} else {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_INCOMING);
}
}
}
}
});
//listen for a click on the send button
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send the message!
messageBody = messageBodyField.getText().toString();
if (messageBody.equals("")) {
Toast.makeText(getApplicationContext(), "Please enter a message", Toast.LENGTH_SHORT).show();
return;
}else {
messageService.sendMessage(recipientId, messageBody);
messageBodyField.setText("");
}
}
});
}
//unbind the service when the activity is destroyed
#Override
public void onDestroy() {
unbindService(serviceConnection);
messageService.removeMessageClientListener(new MyMessageClientListener());
super.onDestroy();
}
private class MyServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(new MyMessageClientListener());
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
}
private class MyMessageClientListener implements MessageClientListener {
//Notify the user if their message failed to send
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
Toast.makeText(getApplicationContext(), "Message failed to send." + failureInfo.getSinchError().getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
//Display an incoming message
if (message.getSenderId().equals(recipientId)) {
WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_INCOMING);
}
}
#Override
public void onMessageSent(MessageClient client, Message message, final String recipientId) {
//Display the message that was just sent
//Later, I'll show you how to store the
//message in Parse, so you can retrieve and
//display them every time the conversation is opened
//WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
//messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
Toast.makeText(getApplicationContext(), "Message successfully senT.", Toast.LENGTH_SHORT).show();
final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
//only add message to parse database if it doesn't already exist there
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereEqualTo("sinchId", message.getMessageId());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
if (messageList.size() == 0) {
ParseObject parseMessage = new ParseObject("ParseMessage");
parseMessage.put("senderId", currentUserId);
parseMessage.put("recipientId", recipientId);
parseMessage.put("messageText", writableMessage.getTextBody());
parseMessage.put("sinchId", writableMessage.getMessageId());
parseMessage.saveInBackground();
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
}
}
}
});
}
//Do you want to notify your user when the message is delivered?
#Override
public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {}
//Don't worry about this right now
#Override
public void onShouldSendPushData(MessageClient client, Message message, List<PushPair> pushPairs) {}
}
}
And this is my MessageService.java
package com.app.knowtes;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import com.parse.ParseUser;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.WritableMessage;
/**
* Created by RR on 12/4/2015.
*/
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "XXXXXXXXXXXXXXXXXXX";
private static final String APP_SECRET = "XXXXXXXXXXXXXXXX";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private Intent broadcastIntent = new Intent("com.app.knowtes.ChatListActivity");
private LocalBroadcastManager broadcaster;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//get the current user id from Parse
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.userId(username)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
//this client listener requires that you define
//a few methods below
sinchClient.addSinchClientListener(this);
//messaging is "turned-on", but calling is not
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
//The next 5 methods are for the sinch client listener
#Override
public void onClientFailed(SinchClient client, SinchError error) {
sinchClient = null;
broadcastIntent.putExtra("success", false);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStarted(SinchClient client) {
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
broadcastIntent.putExtra("success", true);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {}
#Override
public void onLogMessage(int level, String area, String message) {}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
#Override
public void onDestroy() {
sinchClient.stopListeningOnActiveConnection();
//sinchClient.stop();
sinchClient.terminate();
}
//public interface for ListUsersActivity & MessagingActivity
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
public void terminateSinchClient(){
}
}
}
enter code here
When you log out, our servers dont know that the messages have been delivered to that device. We keep messages for delivery for 30 days. AS a developer you will experience this more since you are wiping the install when you deploy.
If you just kill the app and launch it again you will see that its not delivered again.
There is a couple of ways of avoiding this,
1. Dont log out
2. If you want logout functionality, dont toast as old messages arrive look at time stamp.
or keep track of messages id in your own database

Task android sample error

I am download task-android-sample(http://code.google.com/p/google-api-java-client/issues/detail?id=479). But when i run this example on my android device, I m get error
The error appears here in this function
protected void doInBackground() throws IOException {
Log.d(Tag, "doInBackground");
List<String> result = new ArrayList<String>();
List<Task> tasks =
client.tasks().list("#default").setFields("items/title").execute().getItems();
Log.d(Tag, "трассировка");
if (tasks != null) {
for (Task task : tasks) {
result.add(task.getTitle());
}
} else {
result.add("No tasks.");
}
activity.tasksList = result;
}
description client
final com.google.api.services.tasks.Tasks client;
client = activity.service;
in what could be the problem? I am a novice, please help.
04-23 08:55:06.789: E/TasksSample(3778): com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
04-23 08:55:06.789: E/TasksSample(3778): {
04-23 08:55:06.789: E/TasksSample(3778): "code": 403,
04-23 08:55:06.789: E/TasksSample(3778): "errors": [
04-23 08:55:06.789: E/TasksSample(3778): {
04-23 08:55:06.789: E/TasksSample(3778): "domain": "usageLimits",
04-23 08:55:06.789: E/TasksSample(3778): "message": "Access Not Configured",
04-23 08:55:06.789: E/TasksSample(3778): "reason": "accessNotConfigured"
04-23 08:55:06.789: E/TasksSample(3778): }
04-23 08:55:06.789: E/TasksSample(3778): ],
04-23 08:55:06.789: E/TasksSample(3778): "message": "Access Not Configured"
public static final String KEY = null;
make sure that you added key in place of null in ClientCredentials.java
AsyncLoadTasks
package com.google.api.services.samples.tasks.android;
import com.google.api.services.tasks.model.Task;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class AsyncLoadTasks extends CommonAsyncTask {
final String Tag="States";
AsyncLoadTasks(TasksSample tasksSample) {
super(tasksSample);
}
#Override
protected void doInBackground() throws IOException {
Log.d(Tag, "doInBackground");
List<String> result = new ArrayList<String>();
List<Task> tasks =
client.tasks().list("#default").setFields("items/title").execute().getItems();
Log.d(Tag, "трассировка");
if (tasks != null) {
for (Task task : tasks) {
result.add(task.getTitle());
}
} else {
result.add("No tasks.");
}
activity.tasksList = result;
}
static void run(TasksSample tasksSample) {
new AsyncLoadTasks(tasksSample).execute();
}
}
CommonAsyncTask
package com.google.api.services.samples.tasks.android;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityI OException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import java.io.IOException;
abstract class CommonAsyncTask extends AsyncTask<Void, Void, Boolean> {
final String Tag="States";
final TasksSample activity;
final com.google.api.services.tasks.Tasks client;
private final View progressBar;
CommonAsyncTask(TasksSample activity) {
Log.d(Tag, "CommonAsyncTask");
this.activity = activity;
client = activity.service;
progressBar = activity.findViewById(R.id.title_refresh_progress);
}
#Override
protected void onPreExecute() {
Log.d(Tag, "onPreExecute");
super.onPreExecute();
activity.numAsyncTasks++;
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected final Boolean doInBackground(Void... ignored) {
Log.d(Tag, "Boolean doInBackground");
try {
doInBackground();
return true;
} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
Log.d(Tag, "1");
activity.showGooglePlayServicesAvailabilityErrorDialog(
availabilityException.getConnectionStatusCode());
} catch (UserRecoverableAuthIOException userRecoverableException) {
Log.d(Tag, "2");
activity.startActivityForResult(
userRecoverableException.getIntent(), TasksSample.REQUEST_AUTHORIZATION);
} catch (IOException e) {
Log.d(Tag, "3");
Utils.logAndShow(activity, TasksSample.TAG, e);
}
return false;
}
#Override
protected final void onPostExecute(Boolean success) {
Log.d(Tag, "onPostExecute");
super.onPostExecute(success);
if (0 == --activity.numAsyncTasks) {
progressBar.setVisibility(View.GONE);
}
if (success) {
activity.refreshView();
}
}
abstract protected void doInBackground() throws IOException;
}
TasksSample
package com.google.api.services.samples.tasks.android;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.tasks.TasksScopes;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class TasksSample extends Activity {
private static final Level LOGGING_LEVEL = Level.OFF;
private static final String PREF_ACCOUNT_NAME = "accountName";
static final String TAG = "TasksSample";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = new GsonFactory();
GoogleAccountCredential credential;
List<String> tasksList;
ArrayAdapter<String> adapter;
com.google.api.services.tasks.Tasks service;
int numAsyncTasks;
private ListView listView;
final String Tag="States";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Tag, "onCreate");
// enable logging
Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
// view and menu
setContentView(R.layout.calendarlist);
listView = (ListView) findViewById(R.id.list);
// Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, TasksScopes.TASKS);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// Tasks client
service =
new com.google.api.services.tasks.Tasks.Builder(transport, jsonFactory, credential)
.setApplicationName("Google-TasksAndroidSample/1.0").build();
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(Tag, "run");
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, TasksSample.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
void refreshView() {
Log.d(Tag, "refreshView");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tasksList);
listView.setAdapter(adapter);
}
#Override
protected void onResume() {
Log.d(Tag, "onResume");
super.onResume();
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(Tag, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
AsyncLoadTasks.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
AsyncLoadTasks.run(this);
}
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(Tag, "onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(Tag, "onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.menu_refresh:
AsyncLoadTasks.run(this);
break;
case R.id.menu_accounts:
chooseAccount();
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean checkGooglePlayServicesAvailable() {
Log.d(Tag, "checkGooglePlayServicesAvailable");
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
private void haveGooglePlayServices() {
Log.d(Tag, "haveGooglePlayServices");
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
Log.d(Tag, "user to choose account");
// ask user to choose account
chooseAccount();
} else {
Log.d(Tag, "load calendars");
// load calendars
AsyncLoadTasks.run(this);
}
}
private void chooseAccount() {
Log.d(Tag, "chooseAccount");
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
}
Utils
package com.google.api.services.samples.tasks.android;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import android.app.Activity;
import android.content.res.Resources;
import android.util.Log;
import android.widget.Toast;
public class Utils {
public static void logAndShow(Activity activity, String tag, Throwable t) {
// Log.d(Tag, "onPostExecute");
Log.e(tag, "Error", t);
String message = t.getMessage();
if (t instanceof GoogleJsonResponseException) {
GoogleJsonError details = ((GoogleJsonResponseException) t).getDetails();
if (details != null) {
message = details.getMessage();
}
} else if (t.getCause() instanceof GoogleAuthException) {
message = ((GoogleAuthException) t.getCause()).getMessage();
}
showError(activity, message);
}
/**
public static void logAndShowError(Activity activity, String tag, String message) {
String errorMessage = getErrorMessage(activity, message);
Log.e(tag, errorMessage);
showErrorInternal(activity, errorMessage);
}
public static void showError(Activity activity, String message) {
String errorMessage = getErrorMessage(activity, message);
showErrorInternal(activity, errorMessage);
}
private static void showErrorInternal(final Activity activity, final String errorMessage) {
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG).show();
}
});
}
private static String getErrorMessage(Activity activity, String message) {
Resources resources = activity.getResources();
if (message == null) {
return resources.getString(R.string.error);
}
return resources.getString(R.string.error_format, message);
}
}
It is my code. What I can fix?

onActivityResult in a non-activity class?

I am trying to implement facebook login and wall post in Android, so I created a non-activity class that handles everything. I saw all these examples where they use this method - onActivityResult but I don't know if I have to use it or why it's so important. Code works without it as long as I don't have the facebook app installed on the phone and I wonder if onActivityResult have anything to do with it. PS: I'm pretty sure I generated the hash key corectly. Thank you. :)
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.infobest.praiser.R;
import com.infobest.praiser.utils.Constants;
/**
* Functionality for facebook sharing
*
* #author oana_balaceanu
*
*/
public class ShareFacebook
{
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private Facebook facebook;
private String messageToPost;
private Context ctx;
public ShareFacebook(String messageToPost, Context ctx)
{
this.messageToPost = messageToPost;
this.ctx = ctx;
}
public boolean saveCredentials(Facebook facebook)
{
Editor editor = ctx.getSharedPreferences(Constants.KEY, Context.MODE_PRIVATE).edit();
editor.putString(Constants.TOKEN, facebook.getAccessToken());
editor.putLong(Constants.EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook)
{
SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(Constants.TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(Constants.EXPIRES, 0));
return facebook.isSessionValid();
}
public void share()
{
facebook = new Facebook(Constants.APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid())
{
loginAndPostToWall();
}
else
{
postToWall(messageToPost);
}
}
public void loginAndPostToWall()
{
facebook.authorize((Activity) ctx, PERMISSIONS,
(DialogListener) new LoginDialogListener());
}
public void postToWall(String message)
{
FacebookPoster fp = new FacebookPoster();
fp.execute(message, null, null);
}
private class FacebookPoster extends AsyncTask<String, Object, Object>
{
#Override
protected Object doInBackground(String... message)
{
Bundle parameters = new Bundle();
parameters.putString("message", message[0]);
parameters.putString("link", ctx.getResources().getString(R.string.rateLink));
parameters.putString("picture", ctx.getResources().getString(R.string.linkIconPicture));
try
{
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false"))
{
return ctx.getResources().getString(R.string.facebookError);
}
else
{
return ctx.getResources().getString(R.string.facebookSuccess);
}
}
catch (Exception e)
{
Log.d("ShareOnFacebook", e.toString());
return ctx.getResources().getString(R.string.facebookError);
}
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
showToast(result);
}
}
class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
saveCredentials(facebook);
if (messageToPost != null)
{
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onError(DialogError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onCancel()
{
showToast(ctx.getResources().getString(R.string.facebookCancel));
}
}
private void showToast(Object message)
{
Toast.makeText(ctx, message.toString(), Toast.LENGTH_SHORT).show();
}
}
If you test your app on emulator or smartphone with installed Facebook app, login will fail because of it.

Categories

Resources