Android: onReceiveResult is not triggered - android

I'm trying to get some data from a Service that gets an address from coordinates. I followed the step by step official android tutorial about this (http://developer.android.com/training/location) but i'm stuck. I'm sending the data from the Service class to the Activity using the send method but the onReceiveResult method doesn't seem to trigger. Here's my Service class:
public class FetchAddressIntentService extends IntentService {
protected ResultReceiver mReceiver;
public FetchAddressIntentService(String name) {
super(name);
}
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
// Get the location passed to this service through an extra.
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
mReceiver = new ResultReceiver(new Handler());
List < Address > addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); //we want 1 result
} catch (IOException ioException) {
errorMessage = getString(R.string.service_not_available);
Log.e("TAG", errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e("TAG", errorMessage + ". " + "Latitude = " + location.getLatitude() + ", Longitude = " + location.getLongitude(), illegalArgumentException);
}
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e("TAG", errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
Address address = addresses.get(0);
ArrayList < String > addressFragments = new ArrayList < String > ();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
Log.i("TAG", getString(R.string.address_found) + ": " + addressFragments.get(0));
deliverResultToReceiver(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.separator"), addressFragments));
}
}
private void deliverResultToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
mReceiver.send(resultCode, bundle);
}
}
And the relevant part of my Activity:
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
Log.i("address", mAddressOutput);
address.setText(mAddressOutput);
if (resultCode == Constants.SUCCESS_RESULT) {
Toast.makeText(LocationActivity.this, getString(R.string.address_found),
Toast.LENGTH_LONG).show();
}
}
}

You need to create receiver in Activity
private AddressResultReceiver mReceiver;
#Override
protected void onResume() {
super.onResume();
mReceiver = new AddressResultReceiver(new Handler());
mReceiver.setReceiver(this);
}
and pass to Intent service
public void onStarService() {
final Intent intent = new Intent("SOME_COMMAND_ACTION", null, this, FetchAddressIntentService.class);
intent.putExtra("RECEIVER", mReceiver);
startService(intent);
}
and in FetchAddressIntentService
#Override
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("RECEIVER");
/// your code
}

The problem is with this line:
mReceiver = new ResultReceiver(new Handler());
Replace it with this:
mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
The problem is that you're creating a new ResultReceiver instead of using the one that is presumably passed in as an Intent extra from this code:
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
startService(intent);
}
So, just use the one passed in as an extra in the Intent, and it should work.

Related

Cannot get android service to start at bootup

I have a boot receiver starting a service and also I can start and stop the service within the app.
But when I boot up the phone the service does start but stops instantly after starting. I have set the return on onStartCommand to START_STICKY.
This is my boot receiver:
public void onReceive(final Context context, final Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Toast.makeText(context, "Boot received", Toast.LENGTH_LONG).show();
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
this.mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
this.encryption = new Encryption(mTelephonyMgr, sharedPreferences);
//startService(context);
Intent i = new Intent(context, ProfileActivity.class);
i.putExtra("boot_received", false);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
sharedPreferences.edit().putBoolean(Keys.AVAILABILITY, false).apply();
}
}
public void startService(final Context context){
final Intent intent = new Intent(context, PhoneCallService.class);
// If no token, try getting one.
if (Keys.phoneServiceToken == null || Keys.phoneServiceToken.isEmpty()) {
getToken(context, new Callbacks.ReceivePhoneServiceTokenCallback() {
#Override
public void receivePhoneServiceTokenCallback(boolean gotToken) {
if (gotToken) {
intent.putExtra(Keys.PHONE_SERVICE_TOKEN_EXTRA, Keys.phoneServiceToken);
intent.setAction(PhoneCallService.START_SERVICE);
context.startService(intent);
} else {
Log.d(LOG_TAG, String.valueOf(R.string.unexpected_error));
}
}
});
} else {
intent.putExtra(Keys.PHONE_SERVICE_TOKEN_EXTRA, Keys.phoneServiceToken);
intent.setAction(PhoneCallService.START_SERVICE);
context.startService(intent);
}
}
public void getToken(Context context, final Callbacks.ReceivePhoneServiceTokenCallback callback){
final String API = Keys.getpvmURL() + SharedResources.URL_DIRECT_CALL_TOKEN;
JsonObject json = encryption.getID();
json.addProperty("versionCode", BuildConfig.VERSION_CODE);
Ion.with(context)
.load(API)
.setTimeout(Keys.TIMEOUT_DIRECT_CALL_TOKEN)
.setJsonObjectBody(json)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
if(e == null) {
Log.d(LOG_TAG, "No Exceptions");
if(result.getHeaders().code() == 200) {
if(result.getResult().has("result")) {
Keys.phoneServiceToken = result.getResult().get("result").getAsString();
callback.receivePhoneServiceTokenCallback(true);
} else {
Log.w(LOG_TAG, "Does not have result");
callback.receivePhoneServiceTokenCallback(false);
}
} else {
Log.w(LOG_TAG, "Not getting 200 " + result.getHeaders().message());
callback.receivePhoneServiceTokenCallback(false);
}
} else {
Log.e(LOG_TAG, "Exception has occurred " + e.getClass());
callback.receivePhoneServiceTokenCallback(false);
}
}
});
This is my onStart and onCreate methods:
#Override
public void onCreate() {
Log.d(LOG_TAG, "Service started");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(PhoneCallService.this);
notificationManager = (NotificationManager) PhoneCallService.this.getSystemService(Context.NOTIFICATION_SERVICE);
voiceBroadcastReceiver = new VoiceBroadcastReceiver();
registerReceiver();
audioManager = (AudioManager) PhoneCallService.this.getSystemService(Context.AUDIO_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent == null || intent.getAction() == null) {
Log.d(LOG_TAG, "No Action");
}
else if (intent.getAction().equals(START_SERVICE)) {
Log.d(LOG_TAG, "Starting PhoneCallService");
accessToken = intent.getStringExtra(Keys.PHONE_SERVICE_TOKEN_EXTRA);
Log.d(LOG_TAG, accessToken);
if (accessToken != null && !accessToken.isEmpty()) {
registerForCallInvites();
MyFcmListenerService.availableToCall = true;
} else {
stopSelf();
MyFcmListenerService.availableToCall = false;
}
}
else if (intent.getAction().equals(STOP_SERVICE)) {
stopSelf();
MyFcmListenerService.availableToCall = false;
}
else if (intent.getAction().equals(ACTION_INCOMING_CALL)) {
handleIncomingCallIntent(intent);
}
else {
Log.d(LOG_TAG, intent.getAction());
}
return START_STICKY;
}
For some reason I just can't get it to work on the boot request.

Send service result to activity

I've got a BroadcastReceiver which checks if Internet connection is available then it starts a service which retrieves an ArrayList from the DB:
public class NetworkWatcher extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Intent retrieveVehicleList = new Intent(context, RetrieveVehicleListService.class);
if (info != null)
{
if (info.isConnected())
{
context.startService(retrieveVehicleList);
}
else
{
context.stopService(retrieveVehicleList);
}
}
}
}
public class RetrieveVehicleListService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
private ArrayList<Vehicle> vehicles;
private void parseVehiclesFromMap(ArrayList vehicles)
{
for (int i = 0; i < vehicles.size(); i++)
{
final Vehicle v = new Vehicle();
HashMap vehicleMap = (HashMap) vehicles.get(i);
v.setPlate(vehicleMap.get("plate").toString());
v.setKm(vehicleMap.get("km") == null ? null : Integer.parseInt(vehicleMap.get("km").toString()));
v.setFuelQuantity(Double.parseDouble(vehicleMap.get("fuel_quantity").toString()));
v.setEffectiveFuelEconomy(Double.parseDouble(vehicleMap.get("fuel_economy").toString()));
v.setInsuranceDate(vehicleMap.get("insurance_date") == null ? null : new LocalDate(vehicleMap.get("insurance_date").toString()));
v.setMatriculationDate(new LocalDate(vehicleMap.get("matriculation_date").toString()));
v.setLatitude(vehicleMap.get("latitude") == null ? null : Double.parseDouble(vehicleMap.get("latitude").toString()));
v.setLongitude(vehicleMap.get("longitude") == null ? null : Double.parseDouble(vehicleMap.get("longitude").toString()));
v.setFuelType(FuelType.fromInt(Integer.parseInt(vehicleMap.get("id_fuel").toString())));
this.vehicles.add(v);
}
}
private void sendRequest(int userID)
{
Response.Listener<String> listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
HashMap json = new ObjectMapper().readValue(response, HashMap.class);
String errorCode = json.get("error_code").toString();
switch (errorCode)
{
case "0":
parseVehiclesFromMap((ArrayList) json.get("vehicles"));
break;
default:
// TODO gestire
break;
}
}
catch (IOException e)
{
// TODO gestire
e.printStackTrace();
}
}
};
VehicleListRequest request = new VehicleListRequest(String.valueOf(userID), listener, null);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
#Override
protected void onHandleIntent(Intent intent)
{
SharedPreferences sp = getSharedPreferences(getString(clyky.cartracker.R.string.sharedPreferencesName), Context.MODE_PRIVATE);
int userID = sp.getInt("id_user", SplashActivity.DEFAULT_USER_ID);
if (userID != SplashActivity.DEFAULT_USER_ID)
{
sendRequest(userID);
}
}
public RetrieveVehicleListService()
{
super("RetrieveVehicleList");
vehicles = new ArrayList<>();
}
}
I want my MainActivity gets that ArrayList from RetrieveVehicleListService when the activity is started. How could I do that?
Thanks in advance.
Use LocalBroadcast reciever to send data from service to activity. Add following code to your activty
private BroadcastReceiver BReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
//put here whaterver you want your activity to do with the intent received
ArrayList<String> arrayList=intent.getStringArrayListExtra("arrayList");
}
};
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
}
protected void onPause (){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
}
and use following method to send broadcast from service
private void sendBroadcast (boolean success){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("success", success);
intent.putStringArrayListExtra("arrayList", arrayList);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Use Local Broadcast Receiver :
send broadcast using below code
Intent intent = new Intent("YourAction");
Bundle bundle = new Bundle();
bundle .putSerializable("ARRAYLIST",(Serializable)vehicles);
intent.putExtra("BUNDLE",bundle);
intent.putExtras(intent)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
And receive broadcast in your activity:
private MyBroadcastReceiver myReceiver;
#Override
public void onResume(){
myReceiver = new MyReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause(){
if(myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Here you have the received broadcast
// And if you added extras to the intent get them here too
// this needs some null checks
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>)args.getSerializable("ARRAYLIST");
}
}

InstantiationException: has no zero argument constructor?

I'm trying to display a location address in google map but when i start Intent Service for the fetching address it will show error "Unable to instantiate service" .
i use this link for Displaying a Location Address.
https://developer.android.com/training/location/display-address.html
this is my code:
public class FetchAddressIntentService extends IntentService {
protected ResultReceiver mReceiver;
public FetchAddressIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
String errorMessage="";
Geocoder geocoder=new Geocoder(this, Locale.getDefault());
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
List<Address> addresses=null;
try {
addresses=geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
} catch (IOException e) {
errorMessage="unhendle IO exception";
e.printStackTrace();
}
if(addresses==null && addresses.size()==0){
if(errorMessage.isEmpty()){
errorMessage="no address found";
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
}
else{
Address address=addresses.get(0);
ArrayList<String> arrayListFrag=new ArrayList<>();
for (int i=0;i<address.getMaxAddressLineIndex();i++){
arrayListFrag.add(address.getAddressLine(0));
}
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"),
arrayListFrag));
}
}
private void deliverResultToReceiver(int successResult, String message) {
Bundle bundle=new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY,message);
mReceiver.send(successResult,bundle);
}
}
here i start intent Service:
protected void startIntentService(){
Intent intent=new Intent(this,FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA,mLastLocation);
startService(intent);
}
public void fetchAddressButtonHandler(){
if(mGoogleApiClient.isConnected() && mLastLocation!=null){
startIntentService();
}
}
Replace:
public FetchAddressIntentService(String name) {
super(name);
}
with:
public FetchAddressIntentService() {
super("whatever you want to use here");
}
(replacing the string with something suitable for your app)
You need to add an zero argument constructor to your class FetchAddressIntentService that takes no arguments:
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}

android not getting calls on the other side when using gcm and sinch sdk

I'm trying to use gcm to start calls in sinch, I send the push notification and I get it on the other side but when I try to start a call I get null pointer exception in my service at mCall.addCallListener( );
this is the part of the gcm intent service where I get the notification and start sinch service :
{
String callId = intent.getExtras().getString("callId");
Intent intent3 = new Intent(this, SinchClientService.class);
intent3.setAction(SinchClientService.ACTION_START_CALL);
intent3.putExtra(SinchClientService.INTENT_EXTRA_CALLID, callId);
startService(intent3);
}
this is what I do in the sinch service:
else if(intent.getAction().equals(ACTION_START_CALL))
{
String callId = intent.getStringExtra(INTENT_EXTRA_CALLID);
if(callId != null)
{
startCall(callId);
}
}
public void startCall(String callId) {
if (mCallClient != null) {
Call call = mCallClient.getCall(callId);
CurrentCall.currentCall = call;
Intent intent = new Intent(this, CallService.class);
startService(intent);
}
}
and this is how I start sinch client:
private void startSinchClient(String id, String userName) {
mSinchClient = Sinch.getSinchClientBuilder().context(this).userId(id).
applicationKey(APP_KEY).applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
mSinchClient.addSinchClientListener(this);
mSinchClient.setSupportCalling(true);
mSinchClient.setSupportMessaging(true);
mSinchClient.setSupportPushNotifications(true);
mSinchClient.setSupportActiveConnectionInBackground(false);
//mSinchClient.startListeningOnActiveConnection();
mMessageClient = mSinchClient.getMessageClient();
mMessageClient.addMessageClientListener(this);
mCallClient = mSinchClient.getCallClient();
mCallClient.addCallClientListener(this);
mSinchClient.checkManifest();
mSinchClient.start();
}
and this is my onIcommingCall method:
#Override
public void onIncomingCall(CallClient client, Call call) {
Log.d(TAG, "Incoming call");
CurrentCall.currentCall = call;
Intent intent = new Intent(this, CallService.class);
startService(intent);
}
and this is the part of my call service where I get null pointer exception:
if(CurrentCall.currentCall == null)
stopSelf();
mCall = CurrentCall.currentCall;
mCall.addCallListener(this);
Note: my call service implements call listener
I never get the call, can someone help me?
Edit this is how I initialize a call:
in the sinch service:
public void callFriend(String id) {
if (mCallClient != null) {
Call call = mCallClient.callUser(id);
CurrentCall.currentCall = call;
Intent intent = new Intent(this, CallService.class);
startService(intent);
}
}
in the call service:
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
Log.d(LOG_TAG, "Should send push notification");
Log.d("payload", pushPairs.get(0).getPushPayload());
asyncTask = new sendPushNotifications(this, call.getRemoteUserId(), pushPairs, call.getCallId());
asyncTask.execute();
}
class sendPushNotifications extends AutoAsyncTask {
List<PushPair> pushPairs;
String message;
String senderId;
String message_id;
String time_stamp;
String callId;
public sendPushNotifications(Context context, String senderId, List<PushPair> pushPairs, String callId) {
super(context, false);
this.pushPairs = pushPairs;
this.senderId = senderId;
this.callId = callId;
}
#Override
protected Integer doInBackground(Void... params) {
boolean connectedToInternet = connManager.getNetworkInfo( ConnectivityManager.TYPE_WIFI).isConnected()
|| connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
if (connectedToInternet)
{
String regId;
//JSONArray arrayList = new JSONArray();
for(PushPair p: pushPairs)
{
regId = new String(p.getPushData());
//arrayList.put(regId);
UserFunctions.sendCallPushNotifications(senderId, regId, "call", callId);
}
asyncTask = null;
return 0;
}
else
{
asyncTask = null;
return 1;
}
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 0)
{
Log.d("call push sent", "sent");
}
else if (result == 1)
{
Toast.makeText(getApplicationContext(),
"No Network Connection !!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(
getApplicationContext(),
"Error occured,Please Try Again Later !!",
Toast.LENGTH_SHORT).show();
}
}
}
}
latest edit so I did what you said and I only get calls in the messaging activity, my new codes are:
in the call service:
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
Log.d(LOG_TAG, "Should send push notification");
Log.d("payload", pushPairs.get(0).getPushPayload());
asyncTask = new sendPushNotifications(this, call.getRemoteUserId(), pushPairs, call.getCallId());
asyncTask.execute();
}
class sendPushNotifications extends AutoAsyncTask {
List<PushPair> pushPairs;
String message;
String senderId;
String message_id;
String time_stamp;
String callId;
public sendPushNotifications(Context context, String senderId, List<PushPair> pushPairs, String callId) {
super(context, false);
this.pushPairs = pushPairs;
this.senderId = senderId;
this.callId = callId;
}
#Override
protected Integer doInBackground(Void... params) {
boolean connectedToInternet = connManager.getNetworkInfo( ConnectivityManager.TYPE_WIFI).isConnected()
|| connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
if (connectedToInternet)
{
String regId;
String payload;
//JSONArray arrayList = new JSONArray();
for(PushPair p: pushPairs)
{
regId = new String(p.getPushData());
payload = new String(p.getPushPayload());
//arrayList.put(regId);
UserFunctions.sendCallPushNotifications(senderId, regId, "call", callId, payload);
}
asyncTask = null;
return 0;
}
else
{
asyncTask = null;
return 1;
}
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 0)
{
Log.d("call push sent", "sent");
}
else if (result == 1)
{
Toast.makeText(getApplicationContext(),
"No Network Connection !!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(
getApplicationContext(),
"Error occured,Please Try Again Later !!",
Toast.LENGTH_SHORT).show();
}
}
}
the gcm intent service:
else
{
String callId = intent.getExtras().getString("callId");
String payload = intent.getExtras().getString("payload");
Intent intent3 = new Intent(this, SinchClientService.class);
intent3.setAction(SinchClientService.ACTION_START_CALL);
intent3.putExtra(SinchClientService.INTENT_EXTRA_CALLID, callId);
intent3.putExtra(SinchClientService.INTENT_EXTRA_PAYLOAD, payload);
startService(intent3);
}
the sinch service:
else if(intent.getAction().equals(ACTION_START_CALL))
{
String callId = intent.getStringExtra(INTENT_EXTRA_CALLID);
if(callId != null)
{
startCall(callId);
}
}
public void startCall(String callId) {
/*if (mCallClient != null) {
Call call = mCallClient.getCall(callId);
CurrentCall.currentCall = call;
Intent intent = new Intent(this, CallService.class);
startService(intent);
}*/
if(INTENT_EXTRA_PAYLOAD != null)
{
if(mSinchClient.isStarted())
mSinchClient.relayRemotePushNotificationPayload(INTENT_EXTRA_PAYLOAD);
else
{
DatabaseHandler handler = new DatabaseHandler(this);
UserInfo info = handler.getUserDetails();
startSinchClient(String.valueOf(info.uid), info.name);
String gcm_regId = ChatDatabaseHandler.getInstance(this).getGcmRegId();
mSinchClient.registerPushNotificationData(gcm_regId.getBytes());
}
}
}
#Override
public void onIncomingCall(CallClient client, Call call) {
Log.d(TAG, "Incoming call");
/*if(INTENT_EXTRA_CALLID != null)
{
CurrentCall.currentCall = mCallClient.getCall(INTENT_EXTRA_CALLID);
INTENT_EXTRA_CALLID = null;
}*/
CurrentCall.currentCall = call;
Intent intent = new Intent(this, CallService.class);
startService(intent);
}
that is also what I do when I bind and unbind with the service:
#Override
public boolean onUnbind(Intent intent) {
mSinchClient.stopListeningOnActiveConnection();
return super.onUnbind(intent);
}
#Override
public IBinder onBind(Intent intent) {
mSinchClient.startListeningOnActiveConnection();
return mServiceInterface;
}
You seem to be missing the code where you actually send the Sinch-specific payload in your push, you should use PushPair.getPushPayload() to retrieve it in the onShouldSendPushNotification callback and make sure to include that in the push message.
After you add that, you need to retrieve the payload on the receiver side and pass in to relayRemotePushNotificationPayload(String payload). This will give you the onIncomingCall callback on the receiver side.

using threads in class

hii i am developing an app in which i m getting locations and speed. now when the user in speed , i m showing a screen in front of user on which user has 2 buttons. and doing same in a zone which we make restricted. user has to send sms to parent if he is in speed or zone.
but i m getting a problem that as user got speed my screen is not coming, phone got hanged and app is in App not responding mode. i apply threading for this also but didn't get succeed , please check my code and guide me is there is anything goes wrong.if the first screen is coming than on click of button it is going in same situation as above.
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
}
}
}
i also put a thread in on button click method.
please guide me if anything goes wrong.
thanks in advance
pls check this answer
public class CheckLocation extends Service{
private static final String TAG = "CheckLocation";
private LocationManager lm;
LocationListener locationListener;
private float speed,speedinMiles,Speedvalue,lastSpeed;
private double lattitude=25.66;
private double longtitude=32.45;
private Context context;
String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
String []child,parentNumber;
String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
String speedAlert=SERVER ADDRESS FOR SENDING MAIL
PendingIntent pendingIntent;
CursorHandler cursorHandler;
boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
JSONArray jArray;
JSONObject json_data=new JSONObject();
SendingSmsEmail sendingSmsEmail;
int enter=0,exit=0,speedIntent=0;
public CheckLocation(Context context)
{
this.context = context;
}
public CheckLocation()
{
Log.d(TAG,"in constructor of check location");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "onCreate()");
super.onCreate();
cursorHandler=new CursorHandler(this);
TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = telephonyManager.getDeviceId();
Log.d(TAG,"imei number of phone..got it.."+IMEI);
status=getStatus();
Log.d(TAG, "status of speed sms.."+status);
Log.d(TAG, "starting service");
startService();
}
private void startService()
{
Log.d(TAG, "startService()");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Log.d(TAG, "calling location listener");
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onLocationChanged()");
if (loc != null)
{
lattitude=loc.getLatitude();
longtitude=loc.getLongitude();
lastSpeed = speed;
speed = loc.getSpeed();
// CHANGING SPPEED IN MILES PER SECOND
speedinMiles=(float) (speed*2.2369362920544);
Log.d(TAG, "speed in miles.."+speedinMiles);
loc.setSpeed(speedinMiles);
//BROADCASTING SPEED INTENT
Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
intent.putExtra("speed", speedinMiles);
intent.putExtra("lattitude",lattitude);
intent.putExtra("longitude", longtitude);
sendBroadcast(intent);
Log.d(TAG, "Intent Broad casted");
//SAVING LOCATION DATA IN DATABSE
saveData(lattitude,longtitude);
// CHECKING SPEED
if(speedinMiles>20)
{
new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
}
else
{
Log.d(TAG, "user is not in speed ");
speedIntent=0;
}
}
}
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled,enableing network provider");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
Log.d(TAG, "Network provider enabled");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged)");
}
}
public float getCurrentSpeed() {
return speedinMiles;
}
public double getCurrentLattitude() {
return lattitude;
}
public double getCurrentLongitude() {
return longtitude;
}
public float getLastSpeed() {
return lastSpeed;
}
private String getStatus()
{
//child=conntectionHandler.post(childstatus);
child=cursorHandler.getData("status");
for (int i = 0; i < child.length; i++)
{
Log.d(TAG,"status["+i+"]"+child[i]);
speedStatus=child[i];
System.out.println("status."+speedStatus);
}
wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
System.out.println("speed alert is.."+wantSpeedAlert);
return wantSpeedAlert;
}
void saveData(double lattitude2, double longtitude2)
{
try{
Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);
addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
Log.d(TAG,"completeServerAdd.."+addwithData);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(addwithData);
HttpResponse response = httpclient.execute(httpGet);
Log.d(TAG, response.toString());
Log.d(TAG,"server Connected");
Log.i(TAG,"data inserted");
}
catch(Exception e)
{
Log.e(TAG, "Error converting result "+e.getMessage());
}
}
private class CheckSpeedTask extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... status)
{
Log.d(TAG, "CHECK SPEED TASK");
String statusForMail=status[0];
if(statusForMail.equalsIgnoreCase("y"))
{
System.out.println("speed Alert status is..."+statusForMail);
if(speedIntent==0)
{
//sending mail and sms to parent
alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
Log.d(TAG, "address for speed alert."+alertAdd);
Log.d(TAG, "prompting server ");
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet=new HttpGet(alertAdd);
HttpResponse response = httpClient.execute(httpGet);
Log.d(TAG,"mail send");
speedIntent=1;
}
catch (Exception e)
{
Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
else
{
Log.d(TAG, "speed intent value is 1 so not sending mail");
}
}
else
{
Log.d(TAG, "Speed alert status is negative");
}
Log.d(TAG, "Starting Intent");
Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplicationContext().startActivity(screenIntent);
Log.d(TAG, "new Activity Starts");
return null;
}
}
}
}

Categories

Resources