Gps,GeoCoding causes app hang in android - android

I am using locationListener with Gps.When my Gps symbol gets stable(i.e stop blinking) means it has got the new location ,at that time it hangs my app for a while.I am using locationListener in Service.But when I run "Maps" application(google maps.apk application) it runs smoothly on Gps.so Whats is the problem whit my app that runs very smoothly if Gps is off.
My Code is here
public class LocationUpdateService extends Service implements IActionController{
private LocationManager _locationManager;
private String _provider;
private boolean _gpsEnabled;
private boolean _networkEnabled;
private String _json;
private boolean _locationSendingByCheckIn;
private Intent _intent;
int i=1;
//private boolean _locationAvailable;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
i=1;
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",getApplicationContext());
if (tracking_key == null || tracking_key.equals("")||!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
}
else
{
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
getLocation();
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
try {
if(!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext()))
{
stopService(new Intent(getApplicationContext(),LocationUpdateService.class));
return;
}
else if (intent.getExtras() != null)
{
if (intent.getExtras().getBoolean("locationSendingAlarm"))
{
_locationSendingByCheckIn=false;
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER)&&_locationManager!=null&&!_gpsEnabled&&_networkEnabled)
{
_locationManager.removeUpdates(locationListener);
getLocation();
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
else if((_providerOld.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER))&&_gpsEnabled)
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else if(_providerOld.equalsIgnoreCase(""))
{
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
else
{
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS);
}
}
else if(intent.getExtras().getBoolean(AppConstants.APP_REPORT_TYPE_CHECK_IN))
{
_intent=new Intent(AppConstants.CHECK_IN_BROADCAST_RECEIVER);
_locationSendingByCheckIn=true;
sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_CHECK_IN);
}
else if(intent.getExtras().getBoolean(AppConstants.APP_SETTINGS_CHANGED))
{
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
if(_locationManager != null) _locationManager.removeUpdates(locationListener);
getLocation();
}
}
}
catch (Exception e) {
}
}
private void getLocation()
{
try{
_gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
/*if(!_gpsEnabled && !_networkEnabled)
{
}*/
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
_provider = _locationManager.getBestProvider(criteria, false);*/
/* Bundle bundle = new Bundle();
// they would help boost my gps,
boolean xtraInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_xtra_injection",bundle);
boolean timeInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER,
"force_time_injection",bundle);*/
long timeInterval=getTimeInterval();
try
{
if(timeInterval==1000*60)
timeInterval=1000*60*2-1000*20; //100 seconds
else if(timeInterval==1000*60*5)
timeInterval=1000*60*5-1000*30;// 4.5 minutes
else timeInterval=1000*60*5-1000*30; //4.5 minutes
}
catch (Exception e) {
timeInterval=1000*60*5-1000*30; //4.5 min
}
if(_gpsEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,timeInterval,200,locationListener);
return;
}
else if(_networkEnabled)
{
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,timeInterval,200,locationListener);
return;
}
else
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
/*Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(null==location)
{
location = _locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
else if(location != null && location.getProvider()!=null)
{
_locationManager.requestLocationUpdates(location.getProvider(),5*60*1000,0,locationListener);
_locationAvailable=true;
}*/
}
catch(Exception ex)
{
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext());
}
}
/**
*
* Location listener
*/
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/*
Toast.makeText(getApplicationContext(), "status changed", Toast.LENGTH_SHORT).show();
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}*/
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show();
i++;
saveLocation(getApplicationContext(),location);
}
};
public void saveLocation(Context context, Location location)
{
if(location!=null)
{
double _latitude=location.getLatitude();
double _longitude=location.getLongitude();
double _altidude=location.getAltitude();
float _accuracy=location.getAccuracy();
float _bearing=location.getBearing();
float _speed=location.getSpeed() * 3.6f;
long _time=location.getTime();
String _address=getAddress(location);
double _latitudeOld =MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
MySharedPreference.putBoolean(MySharedPreference.IS_LOCATION_STATIC, _latitude == _latitudeOld && _longitude == _longitudeOld, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, (float)_latitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)_longitude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)_altidude, context);
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, _accuracy, context);;;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, _bearing, context);;
MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, _speed, context);; ;
MySharedPreference.putLong(MySharedPreference.PREVIOUS_LOCATION_TIME, _time, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, _address, context);
MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, location.getProvider(), context);
if(NativeHelper.getDistanceInMeter(_latitude, _longitude, _latitudeOld, _longitudeOld) >= 330)
{
sendLocationOnServer( LocationUpdateService.this, AppConstants.APP_REPORT_TYPE_SOS);
setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
}
}
public void sendLocationOnServer(Context context, String reportType)
{
try{
String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",context);
String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", context);
if (tracking_key == null || tracking_key.equals("") ||_providerOld.equals(""))
{
return ;
}
double _latitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context);
double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context);
double _altidudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)0.0, context);
float _accuracyOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, (float)0.0, context);;;
float _bearingOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, (float)0.0, context);;
float _speedOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, (float)0.0, context);; ;
boolean isStatic = MySharedPreference.getBoolean(MySharedPreference.IS_LOCATION_STATIC, false, context);
String _addressOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, "Address not available", context);
RequestAppLocationSending appLocationSending=new RequestAppLocationSending();
appLocationSending.setImei(NativeHelper.getDeviceId(context));
appLocationSending.setBattery((int)TrackMyDeviceUtils.getBatteryLevel(context));
appLocationSending.setLatitude(_latitudeOld);
appLocationSending.setLongitude(_longitudeOld);
appLocationSending.setAltitude((int)_altidudeOld );
appLocationSending.setAccuracy(_accuracyOld);
appLocationSending.setCouse(_bearingOld);
appLocationSending.setSpeed(_speedOld);
appLocationSending.setTracking_key(tracking_key);
appLocationSending.setAddress(_addressOld);
appLocationSending.setDate(TrackMyDeviceUtils.getFormatedDateForLocationSending());
appLocationSending.setReportType(reportType);
appLocationSending.setStatic(isStatic);
if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER))
appLocationSending.setData_source("G");
else
appLocationSending.setData_source("N");
_json= appLocationSending.toJson();
LocationSendingController locationSendingController=new LocationSendingController((IActionController)context, EventType.APP_LOCATION_SENDING);
try {
locationSendingController.requestService(_json);
} catch (Exception e) {
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
/*if(city!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_CITY_NAME, city, getApplicationContext());
else
city=MySharedPreference.getString(MySharedPreference.PREVIOUS_CITY_NAME, "", getApplicationContext());*/
String state=addre.getAdminArea();
if(state==null) state="";
/*if(state!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_STATE_NAME, state, getApplicationContext());
else
state=MySharedPreference.getString(MySharedPreference.PREVIOUS_STATE_NAME, "", getApplicationContext());*/
String country=addre.getCountryName();
if(country==null) country="";
/*if(country!=null)
MySharedPreference.putString(MySharedPreference.PREVIOUS_COUNTRY_NAME, country, getApplicationContext());
else
country=MySharedPreference.getString(MySharedPreference.PREVIOUS_COUNTRY_NAME, "", getApplicationContext());*/
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
private void setLocationSendingAlarm(int alarmId) {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent,0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
}
long timeForAlarm=getTimeInterval();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent);
}
private void cancleAlarm(int alarmId)
{
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent, 0);
try {
alarmManager.cancel(pendingIntent);
}
catch (Exception e) {
}
}
#Override
public Activity getMyActivityReference() {
return null;
}
#Override
public void setScreenData(Object screenData, int event, long time) {
Message msg=new Message();
msg.obj=screenData;
msg.arg1=event;
handler.sendMessage(msg);
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
updateUI(msg);
}
};
public void updateUI(Message o)
{
try{
if(o.obj instanceof MyError) {
switch(((MyError)o.obj).getErrorcode())
{
case MyError.NETWORK_NOT_AVAILABLE:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Network not available");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
break;
}
case MyError.EXCEPTION:
case MyError.UNDEFINED:
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
}
}
else if (o.obj instanceof ResponseAppLocationSending) {
ResponseAppLocationSending responseAppLocationSending=(ResponseAppLocationSending) o.obj;
if(responseAppLocationSending.getResponce().contains("saved"))
{
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Check In Submitted");
_intent.putExtra("LocationPostedSuccessfuly", true);
sendBroadcast(_intent);
}
//else setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
}
else {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
}
}
}
}
catch (Exception e) {
if(_locationSendingByCheckIn)
{
_intent.putExtra("Response","Server not responding. Please try later");
_intent.putExtra("LocationPostedSuccessfuly", false);
sendBroadcast(_intent);
_locationSendingByCheckIn=false;
}
}
_locationSendingByCheckIn=false;
}
private long getTimeInterval()
{
try{
String s=MySharedPreference.getString(MySharedPreference.APP_REPORTING_TIME, "10", getApplicationContext());
int time = Integer.parseInt(s);
if(time<1) time=10;
return time*1000*60;
}
catch (Exception e) {
return 1000*60*10; //10 minutes
}
}
#Override
public void onDestroy()
{
if(_locationManager!=null)
_locationManager.removeUpdates(locationListener);
cancleAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID);
super.onDestroy();
}
}

Finaly I got the solution of my problem.I was doing Geo coding frequently but not in a different thread.So I did this(Did Geo coding in a new Thread)
public void onLocationChanged(final Location location) {
new Thread(new Runnable(){
public void run(){
_address=getAddress(location);
}
}).start();
}
};
private String getAddress(Location location)
{
List<Address> addresses;
try{
addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e) {
try{
addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
return findAddress(addresses);
}
catch (Exception e1) {
return "Address not available";
}
}
//return "Address not available";
}
private String findAddress(List<Address> addresses)
{
String address="Address not available";
if(addresses!=null)
{
for(int i=0;i<addresses.size();i++){
Address addre=addresses.get(i);
String street=addre.getAddressLine(0);
if(null==street)
street="";
String city=addre.getLocality();
if(city==null) city="";
String state=addre.getAdminArea();
if(state==null) state="";
String country=addre.getCountryName();
if(country==null) country="";
address=street+", "+city+", "+state+", "+country;
}
return address;
}
return address;
}
}

Related

Reduce the Bluetooth range of android device programmatically in android studio

I am working on the mobile android application and my phone successfully connects to the ESP32 microcontroller. The ESP32's bluetooth range is high and I want to disconnect my phone's bluetooth if the distance/range between the phone and the hardware is more than 10 meters. I cannot modify ESP32's code to reduce the power range, so is there any way I can reduce the bluetooth's range or make my phone disconnect automatically if it goes above a specific range? Please find my android studio code below that I have so far:
public class ConnectedDevice extends AppCompatActivity {
private BluetoothAdapter myBluetooth = null;
private BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private BluetoothDisconnect bluetoothDisconnect;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connected_device);
new ConnectBT().execute();
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisconnectOnBtnClick();
}
});
bluetoothDisconnect = new BluetoothDisconnect();
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(bluetoothDisconnect, intentFilter);
mButtonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCountDownTimer.cancel();
mTimerRunning = false;
mButtonStop.setVisibility(View.INVISIBLE);
Intent intent = new Intent(ConnectedDevice.this, PairedDevices.class);
startActivity(intent);
}
});
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bluetoothDisconnect);
}
private void DisconnectOnBtnClick() {
if (mReadThread != null) {
mReadThread.stop();
do {
} while (mReadThread.isRunning());
mReadThread = null;
}
try {
btSocket.close();
}
catch(IOException e)
{
Toast.makeText(getApplicationContext(), "Could not disconnect", Toast.LENGTH_SHORT).show();
}
finish();
}
private void sendSMS() {
try {
message = brand + " " + model + " " + licensePlate;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("5089715596",null,message,null,null);
Toast.makeText(this,"Message Sent",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(this, "Could not send message",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private class BluetoothDisconnect extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
sendSMS();
startTimer();
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
mButtonStop.setVisibility(View.VISIBLE);
}
#Override
public void onFinish() {
mTimerRunning = false;
mButtonStop.setVisibility(View.INVISIBLE);
Toast.makeText(ConnectedDevice.this, "Calling", Toast.LENGTH_SHORT).show();
callNumber();
}
}.start();
mTimerRunning = true;
mButtonStop.setText("Stop");
}
#SuppressLint("MissingPermission")
private void callNumber()
{
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
phoneIntent.setData(Uri.parse("tel:5088631994"));
startActivity(phoneIntent);
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute () {
progress = ProgressDialog.show(ConnectedDevice.this, "Connecting...", "Please Wait!!!");
}
#Override
protected Void doInBackground (Void... devices) {
try {
if ( btSocket==null || !isBtConnected ) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
remoteDevice = myBluetooth.getRemoteDevice(address);
btSocket = remoteDevice.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e) {
ConnectSuccess = false;
}
return null;
}
#Override
protected void onPostExecute (Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getApplicationContext(), "Connection Failed. Make sure your device is in range", Toast.LENGTH_SHORT).show();
finish();
}
else {
isBtConnected = true;
mReadThread = new ReadInput();
getCurrentData();
}
progress.dismiss();
}
}
}
Calculated using rssi intensity and power values
public double getDistance(int measuredPower, double rssi) {
if (rssi >= 0) {
return -1.0;
}
if (measuredPower == 0) {
return -1.0;
}
double ratio = rssi * 1.0 / measuredPower;
if (ratio < 1.0) {
return Math.pow(ratio, 10);
} else {
double distance= (0.42093) * Math.pow(ratio, 6.9476) + 0.54992;
return distance;
}
}
how to get power values?
in ScanResult call getTxPower (if your api > 26)
Note:rssi reliability is not 100%, it may be affected by environmental factors
short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
int iRssi = abs(rssi);
// 将蓝牙信号强度换算为距离
double power = (iRssi - 59) / 25.0;
String mm = new Formatter().format("%.2f", pow(10, power)).toString();
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String aa = tvDevices.getText().toString() + "";
if (aa.contains(device.getAddress())) {
return;
} else {
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
short rssi = intent.getExtras().getShort(
BluetoothDevice.EXTRA_RSSI);
int iRssi = abs(rssi);
double power = (iRssi - 59) / 25.0;
String mm = new Formatter().format("%.2f", pow(10, power)).toString();
// tvDevices.append(device.getName() + ":" + device.getAddress() + " :" + mm + "m" + "\n");
}else {
}
}
// search finished
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
//TODO
}
}
};

Create a background service to collect and send positions

I work on a service that need to be stared/stopped from a specific time, collect user's locations and send them to an API.
I start my service like so
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, CONSTANTES.START_HOURS); //6
calendar.set(Calendar.MINUTE, CONSTANTES.START_MINUTES); //30
calendar.set(Calendar.SECOND, CONSTANTES.START_SECOND);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(MainActivity.this, AlarmTask.class).setAction("START_SERVICE"), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
My Receiver
public class AlarmTask extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("STOP_SERVICE")) {
System.out.println("service : got stop instruction");
if (isMyServiceRunning(context, ScheduleOffsetService.class)) {
context.stopService(new Intent(context, ScheduleOffsetService.class));
}
} else if (intent.getAction().equalsIgnoreCase("START_SERVICE")) {
System.out.println("service : got start instruction");
if (!isMyServiceRunning(context, ScheduleOffsetService.class)) {
context.startService(new Intent(context, ScheduleOffsetService.class));
}
}
}
private boolean isMyServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
And my service :
public class ScheduleOffsetService extends Service {
private LocationManager mLocationManager;
private ArrayList<Location> locations = new ArrayList<>();
private String token;
public ScheduleOffsetService() {
}
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
System.out.println("Scheduler location : " + location);
mLastLocation.set(location);
locations.add(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
stopSelf();
}
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60, 10f, mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000 * 60, 10f, mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
PropertyApp app = new PropertyApp(this);
System.out.println("ScheduleOffset token : " + app.getToken());
if (app.getToken() != null) {
token = app.getToken();
} else {
stopSelf();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Scheduler : created");
return START_STICKY;
}
private boolean gpsIsEnable() {
LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
#Override
public void onDestroy() {
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
onEnd();
System.out.println("Scheduler : got destroyed");
super.onDestroy();
}
private void onEnd() {
if (locations.isEmpty()) {
return;
}
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(/*URL*/)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
WebServiceInterface webServiceInterface = retrofit.create(WebServiceInterface.class);
JsonObject object = new JsonObject();
for (int i = 0; i < locations.size(); i++) {
JsonObject content = new JsonObject();
content.addProperty("lat", locations.get(i).getLatitude());
content.addProperty("lng", locations.get(i).getLongitude());
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c);
content.addProperty("date", formattedDate);
object.add(String.valueOf(i), content);
}
String data = object.toString();
Call<ResponseRetrofitIreby> call = webServiceInterface.jetLagService(token, PropertyApp.PARNTER_ID, data);
call.enqueue(new Callback<ResponseRetrofitIreby>() {
#Override
public void onResponse(Call<ResponseRetrofitIreby> call, Response<ResponseRetrofitIreby> response) {
if (response.isSuccessful()) {
System.out.println("RESPONSE : " + response.body().getTrackingPosition().getErreur());
}
}
#Override
public void onFailure(Call<ResponseRetrofitIreby> call, Throwable t) {
t.printStackTrace();
}
});
}
}
The thing is : When the user asks to be tracked, the listener of my service is no longer called.
Moreover, if the user kill the application the service seems to restart, and thus empty my list of locations.
Can someone, explain me do to ?
you can try this library location tracker background

WebSocketClient Fails Only on Mobile Network

My Android app is maintaining a socket connection with the server and this connection works fine when the device is connected to Wi-Fi and fails only when the device is connected to the mobile network. Error trace is as follows
org.java_websocket.exceptions.InvalidFrameException: bad rsv 3
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateSingleFrame(Draft_10.java:308)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateFrame(Draft_10.java:285)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:321)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:164)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:185)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at java.lang.Thread.run(Thread.java:841)
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed: bad rsv 3
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed- code: 1002, reason: bad rsv 3
My code is as follows,
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
public class WebSocketService extends Service {
public static final String WEB_SOCKET_SERVICE_RECEIVER = "com.mydomain.myapp.WebSocketServiceReceiver";
public static final String EXTRA_COMMAND = "extraCommand";
public static final String EXTRA_MESSAGE = "extraMessage";
public static final int COMMAND_STOP = -2;
public static final int COMMAND_SEND_MESSAGE = -3;
public static void stopService(Context context, String message) {
Intent intent = new Intent(WEB_SOCKET_SERVICE_RECEIVER);
intent.putExtra(EXTRA_COMMAND, COMMAND_STOP);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("WebSocketService", "onStartCommand");
if (!mStarted) {
mStarted = true;
mWebSocketClosed = false;
mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WebSocketServiceWakeLock");
pingPackets = new Stack<PingPacket>();
registerReceiver(mReceiver, new IntentFilter(
WEB_SOCKET_SERVICE_RECEIVER));
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("WebSocketService", "onDestroy");
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
protected void startWebSocket() throws URISyntaxException {
Log.d("WebSocketServce", "startWebSocket");
String webSocketBaseURL = BuildSpecificConstants.WEB_SOCKET_BASE_URL;
mWebSocketClient = new WebSocketClient(new URI(webSocketBaseURL
+ "?auth_token="
+ SessionManager.getInstance(getApplicationContext())
.getAPIKey())) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("WebSocketServce", "onOpen");
if (!mWakeLock.isHeld()) {
mWakeLock.acquire();
Log.d("WebSocketService", "WakeLock acquired");
}
startPingProtocol();
if (mPendingMessage != null) {
sendMessage(mPendingMessage);
}
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
}
#Override
public void onWebsocketPong(WebSocket conn, Framedata frame) {
super.onWebsocketPong(conn, frame);
try {
if (frame.getOpcode() == Opcode.PONG) {
if (!pingPackets.isEmpty()) {
PingPacket returnedPing = pingPackets.get(0);
if (returnedPing != null) {
returnedPing.consume();
pingPackets.remove(0);
Log.d("WebSocketService", returnedPing.id
+ " pong received");
failedPingCount = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String message) {
try {
JSONObject eventJson = new JSONObject(message);
Log.d("WebSocketService", "Received: " + message);
String eventType = eventJson
.getString(IncomingMessageParams.EVENT);
if (eventType.equals(EventTypes.NEW_BOOKING)) {
Trip trip = Trip
.decodeJSON(
eventJson
.getJSONObject(BookingsResponseParams.KEY_BOOKING),
eventJson.getJSONObject("passenger"),
eventJson.getJSONArray("locations"),
eventJson.optJSONObject("coupon"),
SessionManager
.getInstance(WebSocketService.this));
Intent intent = new Intent(WebSocketService.this,
IncomingBookingActivity.class);
intent.putExtra(IncomingBookingActivity.EXTRA_BOOKING,
trip);
intent.putExtra(
MainActivity.EXTRA_COUNT_DOWN_TIME,
eventJson
.getInt(IncomingMessageParams.LOOKUP_TIME));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SessionManager.getInstance(getApplicationContext())
.setStatus(DriverStatus.BUSY);
LocationUpdateService
.sendStatusChange(WebSocketService.this);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onError(Exception ex) {
ex.printStackTrace();
Log.d("WebSocketService", "Socket closed: " + ex.getMessage());
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
if (!mWebSocketClosed) {
reconnect();
}
}
if (!mWebSocketClosed) {
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
#Override
public void onClose(int code, String reason, boolean remote) {
Log.d("WebSocketService", "Socket closed- code: " + code
+ ", reason: " + reason);
if (code != CloseFrame.NORMAL) {
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(
mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
reconnect();
}
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
};
if (BuildConfig.FLAVOR.equals("production")) {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
SSLSocketFactory factory = sslContext.getSocketFactory();
try {
mWebSocketClient.setSocket(factory.createSocket());
} catch (IOException e) {
e.printStackTrace();
}
}
mWebSocketClient.connect();
}
protected void startPingProtocol() {
pingCounter = 0;
failedPingCount = 0;
pingRunning = true;
if (pingThread == null || !pingThread.isAlive()) {
pingThread = new Thread(new Runnable() {
#Override
public void run() {
while (pingRunning) {
if (failedPingCount < 3) {
PingPacket packet = new PingPacket(pingCounter);
Log.d("WebSocketService", "sending ping "
+ pingCounter);
pingPackets.add(packet);
packet.sendPing(mWebSocketClient);
pingCounter++;
pingCounter %= Byte.MAX_VALUE;
} else {
stopPingProtocol();
Log.d("WebSocketService", "connection lost");
}
try {
Thread.sleep(AppConstants.PING_SPAWN_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
private void stopPingProtocol() {
if (pingThread != null && pingThread.isAlive()) {
pingRunning = false;
pingThread.interrupt();
for (int i = 0; i < pingPackets.size(); i++) {
pingPackets.get(i).consume();
}
pingPackets.clear();
}
}
protected void reconnect() {
if (mConnectionAttempt < AppConstants.MAX_WEB_SOCKET_RECONNECTS) {
mFallbackHandler = new Handler(Looper.getMainLooper());
mFallbackHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacks(this);
mFallbackHandler = null;
}
try {
stopWebSocket();
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
mConnectionAttempt++;
}
}, AppConstants.WEB_SOCKET_BASE_FALLBACK_TIME * mConnectionAttempt);
} else {
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
}
protected void sendMessage(String message) {
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
mWebSocketClient.send(message);
mConnectionAttempt = 1;
Log.d("WebSocketService", "Send: " + message);
} else {
mPendingMessage = message;
}
}
protected void stopWebSocket() {
Log.d("WebSocketService", "Closing");
mWebSocketClosed = true;
mWebSocketClient.close();
stopPingProtocol();
Editor editor = getSharedPreferences(SharedPrefKeys.APP_PREFERENCES,
MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
}
private WakefulBroadcastReceiver mProviderChangedListener = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Helper.checkNetworkStatus(context)) {
mListenForConnectivity = false;
try {
unregisterReceiver(this);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int command = intent.getIntExtra(EXTRA_COMMAND, -1);
switch (command) {
case COMMAND_STOP:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
stopSelf();
break;
case COMMAND_SEND_MESSAGE:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
break;
default:
break;
}
}
};
Private class,
private class PingPacket { protected byte id;
protected Timer timer;
protected PingPacket(byte id) {
this.id = id;
timer = new Timer();
}
protected void sendPing(WebSocketClient client) {
FramedataImpl1 frame = new FramedataImpl1(Opcode.PING);
frame.setFin(true);
client.sendFrame(frame);
Log.d("WebSocketService", id + " ping sent");
timer.schedule(new TimerTask() {
#Override
public void run() {
failedPingCount++;
Log.d("WebSocketService", "Ping " + id + " failed");
}
}, AppConstants.PING_EXPIRE_DELAY);
}
protected void consume() {
timer.cancel();
timer.purge();
}
}
}
What could possibly be causing this?
The InvalidFrameException with a message "bad rsv 3" implies that the protocol exchanged in the WebSocket connection is wrong. Your stack trace implies that Draft_10 is used, but it is too old.
FYI: You can find other WebSocket client libraries for Android in "Which WebSocket library to use in Android app?".

Application not responding error

I have a tracking app that does tracking based on gps and cell id at every 2 minutes. I have started a service from MainActivity using setRepeting() of AlarmManager. Then inside that service I have written an asynctask.In onPreExecute() I fetch latitude and longitude using gps or cellid. And in doInBackground() i am fetching data from sqlite db and send to server. Even after writing all network related code in asynctask app sometimes says application not responding. and on pressing ok it restart. What can I do to avoid this.
public class SendDataAsync extends Service {
Logger logger ;
Context con;
String level1;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(getApplicationContext(),"in onReceive of GPSLoggerService",
// Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
level1 = String.valueOf(level * 100 / scale);
}
}; // battery level
#Override
public void onCreate() {
// TODO Auto-generated method stub
LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "logs"+ File.separator + "log4j.txt");
logConfigurator.setRootLevel(Level.INFO);
logConfigurator.setLevel("org.apache", Level.INFO);
logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
logConfigurator.setMaxFileSize(1024 * 1024 * 5);
logConfigurator.setImmediateFlush(true);
logConfigurator.configure();
logger = Logger.getLogger(SendDataAsync.class);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try
{
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
}
catch (Exception e) {
// TODO: handle exception
logger.info(e);
}
return super.onStartCommand(intent, flags, startId);
}
FetchCordinates
public class FetchCordinates extends AsyncTask<String, Integer, String> {
private Timer monitoringTimer = null;
private static final int TIMER_DELAY = 1000;
private LocationManager locManager;
private static final int gpsMinTime = 1000;
private static final int gpsMinDistance = 1;
private double latitude = 0.0;
private double longitude = 0.0;
private double altitude = 0.0;
float mps;
float kmh;
SendDataAsync sda;
Runtime runtime1;
Process proc1;
int returnVal1 = 0;
int data_mode = 0;
int myLatitude, myLongitude;
String imeiCellID, datetimeCellID;
String latitude_cellID, longitude_cellID;
public String gpslatitude = null;
public String gpslongitude = null;
public String gpsaltitude = null;
private String speed = null;
private String datetime = null;
private String imeino = null;
private String datatype = null;
private CountDownTimer countDownTimer = null;
DBAdapter db;
int flag;
Context context;
boolean didFindLocation = false;
long id;
public static final String PREFS_NAME = "bp";
public LocationManager mLocationManager;
#Override
protected void onPreExecute() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
data_mode = settings.getInt("data_mode", 1);
startLoggingService();
startMonitoringTimer();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sendData();
} catch (ClientProtocolException e) {
logger.info(e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.info(e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
protected void removeGps()
{
locManager.removeUpdates(locationListener);
}
private void startLoggingService() {
db = new DBAdapter(SendDataAsync.this);
if (locManager == null) {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
//ma = new MainActivity();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setSpeedRequired(true);
criteria.setBearingRequired(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0) {
locManager.requestLocationUpdates(bestProvider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
} else {
final List<String> providers = locManager.getProviders(true);
for (final String provider : providers) {
locManager.requestLocationUpdates(provider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
}
}
}
private void startTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
countDownTimer = new CountDownTimer(20000L, 1000L) {// 15 seconds max
#Override
public void onTick(long millisUntilFinished) {
if (didFindLocation) {
countDownTimer.cancel();
}
}
#Override
public void onFinish() {
if (!didFindLocation) {
removeGps();
if(data_mode==1)
{
monitoringTimer.cancel();
cellID();
}
else {
Toast.makeText(getApplicationContext
(),"GPS : Cant find Location", Toast.LENGTH_LONG).show();
}
stopLoggingService();
}//if
}//inFin
};
countDownTimer.start();
}
// class location listener
private final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location) {
didFindLocation = true;
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
// Toast.makeText(getApplicationContext(),"lat :"+latitude+"longi :"+longitude,
// Toast.LENGTH_LONG).show();
gpsaltitude = String.valueOf(altitude);
gpslatitude = String.valueOf(latitude);
gpslongitude = String.valueOf(longitude);
mps = location.getSpeed();
kmh = (float) (mps * 3.6);
speed = Float.toString(kmh);
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetime = sdfDateTime.format(new Date(location.getTime()));
}
#Override
public void onProviderDisabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderDisabled().");
logger.info("onLocationChanged, ");
}
#Override
public void onProviderEnabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderEnabled().");
logger.info("onProviderEnabled, ");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
AppLog.logString("GPSLoggerService.onStatusChanged().");
logger.info("onStatusChanged, ");
}
};
public void saveData() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeino = tm.getDeviceId();
DBAdapter db=new DBAdapter(SendDataAsync.this);
setFlag();
datatype = String.valueOf(flag);
// --add contact----
db.open();
id = db.insertData(imeino, gpslatitude, gpslongitude, datetime,
gpsaltitude, speed, level1, datatype, "1");
db.close();
}// end of saveData() function
private void startMonitoringTimer() {
monitoringTimer = new Timer();
monitoringTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (longitude != 0.0 && latitude != 0.0) {
monitoringTimer.cancel();
monitoringTimer = null;
// turnGPSOn();
//didFindLocation=false;
saveData();
removeGps();
stopLoggingService();
}
}
},TIMER_DELAY,TIMER_DELAY);
}
public boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
return true;
} else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
public int setFlag() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
boolean firstRecord = settings.getBoolean("firstRecord", false);
boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);
if (firstRecord == true) {
flag = 0;
// Toast.makeText(getBaseContext(),"1st record after installation : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("firstRecord", false).commit();
} else if (firstRecordAfterBoot == true) {
flag = 1;
// Toast.makeText(getBaseContext(),"1st record after boot : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("justBooted", false).commit();
} else {
flag = 2;
// Toast.makeText(getBaseContext(),"regular : "+flag,Toast.LENGTH_LONG
// ).show();
}
return flag;
}
public void cellID() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager
.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetimeCellID = sdfDateTime.format(new Date());
// Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
// ).show();
CellidAsync cellasy=new CellidAsync();
String pass = null;
try {
pass = cellasy.execute(cid,lac).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] arr=pass.split(",");
if (Boolean.valueOf(arr[0])) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeiCellID = tm.getDeviceId();
myLatitude=Integer.valueOf(arr[1]);
myLongitude=Integer.valueOf(arr[2]);
latitude_cellID = String.valueOf((float) myLatitude / 1000000);
longitude_cellID = String.valueOf((float) myLongitude / 1000000);
// Toast.makeText(getBaseContext(),"Lat:"+latitude_cellID+"Long:"+longitude_cellID,Toast.LENGTH_LONG
// ).show();
// DBAdapter db=new DBAdapter(this);
// --add contact----
db.open();
setFlag();
datatype = String.valueOf(flag);
id = db.insertData(imeiCellID, latitude_cellID, longitude_cellID,
datetimeCellID, "null", "null", level1, datatype, "0");
db.close();
// --get all contacts----------
/*db.open();
Cursor c = db.getAllData();
if (c.moveToFirst()) {
do {
//DisplayData(c);
} while (c.moveToNext());
}
db.close();*/
}// if
else {
Toast.makeText(getBaseContext(), "CellID : Can't find Location",
Toast.LENGTH_LONG).show();
}// else
}// cellID
public void sendData() throws ClientProtocolException, IOException
{
//Toast.makeText(getApplicationContext(),"in sendData", Toast.LENGTH_LONG).show();
enableInternet();
setAirplaneMode();
runtime1 = Runtime.getRuntime();
proc1 = runtime1.exec("ping -c 1 some ip");
try {
returnVal1 = proc1.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean reachable1 = (returnVal1==0);
if(reachable1==true)
{
if(isInternetOn())
{
JSONObject jObject=new JSONObject();
try
{
//DBAdapter db=new DBAdapter(this);
db.open();
Cursor cursor=db.getAllData();
if(cursor.moveToFirst())
{
do{
jObject = new JSONObject();
jObject.put("Imei", cursor.getString(1));
jObject.put("Lat", cursor.getString(2));
jObject.put("Long", cursor.getString(3));
jObject.put("Gpsdatetime", cursor.getString(4));
jObject.put("Altitude",cursor.getString(5));
jObject.put("Speed", cursor.getString(6));
jObject.put("Battery", cursor.getString(7));
jObject.put("DataType", cursor.getString(8));
jObject.put("DataSource", cursor.getString(9));
//------------------------------------------------------------------------
String dt=cursor.getString(4).replace(" ","*");
String datatoServer=cursor.getString(1)+","+cursor.getString(2)+","+cursor.getString(3)+","+dt+","+cursor.getString(5)+","+cursor.getString(6)+","+cursor.getString(7)+","+cursor.getString(8)+","+cursor.getString(9);
//Toast.makeText(getApplicationContext(),datatoServer, Toast.LENGTH_LONG).show();
HttpEntity entity1;
HttpClient client1 = new DefaultHttpClient();
String url1 ="http:/url="+datatoServer;
HttpPost request1 = new HttpPost(url1);
StringEntity se1 = new StringEntity(datatoServer);
se1.setContentEncoding("UTF-8");
se1.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
entity1 = se1;
//request1.setEntity(entity1);
HttpResponse response1 = client1.execute(request1);
entity1 = response1.getEntity();
//----------------------------------------------------------------
db.deleteContacts(cursor.getLong(0));
}while(cursor.moveToNext());
}//if
db.close();
}//try
catch (JSONException e)
{
e.printStackTrace();
logger.info(""+e);
}
catch(Exception e)
{
logger.info(""+e);
}
}//if
}//if ping
} //method
public void setAirplaneMode()
{
// Check for Airplane Mode
boolean isEnabled = Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0) == 1;
if (isEnabled) {
// toggle airplane mode
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
}
}
public void enableInternet()
{
try{
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
boolean isEnabled;
if(telephonyManager.getDataState() ==
TelephonyManager.DATA_CONNECTED){
//Toast.makeText(GPSLoggerService.this, "true", Toast.LENGTH_LONG).show();
isEnabled = true;
}else{
//Toast.makeText(GPSLoggerService.this, "false", Toast.LENGTH_LONG).show();
isEnabled = false;
}
if (isEnabled) {
} else {
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod
("setMobileDataEnabled", boolean.class);dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);
}
}
catch(Exception e){
logger.info(""+e);
}
}//enable internet
}//async
private void stopLoggingService() {
this.unregisterReceiver(this.mBatInfoReceiver);
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should be fetching the lat and long in the doInBackground() method, and not in preExecute().
Fetching the location might take some time, and should be done in the background. That is why you have this problem.

getting address in android using web service

iam new to android development.
i have tried to get location address using web service but i got class not found exception when i lunched this code.if any one could please suggest me proper solution for this..
code for service class....
public class MWService extends Service implements LocationListener {
private LocationManager myLocationManager;
private LocationProvider myLocationProvider;
private NotificationManager myNotificationManager;
private long frequency;
private double total_distance = 0;
private Location currentLocation;
public static final String BROADCAST_ACTION = "com.motorvehicle.android";
private final Handler handler = new Handler();
Intent intent;
private GeocoderHelper geocoder = new GeocoderHelper();
private boolean isStart=true;
private Location startLocation,endLocation;
private String startAddress="";
private String endAddress="";
private JSONArray jarray = new JSONArray();
private boolean isInternet;
//private final Handler handler = new Handler();
public void onLocationChanged(Location newLocation) {
try {
System.out.println("latitude current :"+currentLocation.getLatitude());
System.out.println("latitude current :"+currentLocation.getLongitude());
System.out.println("latitude new :"+newLocation.getLatitude());
System.out.println("latitude new :"+newLocation.getLongitude());
System.out.println("distance total :"+total_distance);
//System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
double diff = 0.0;
diff = currentLocation.getLatitude()- newLocation.getLatitude();
System.out.println("difference ::"+diff);
if(diff != 0){
total_distance = total_distance + currentLocation.distanceTo(newLocation);
}
if(isStart){
isStart = false;
startLocation = newLocation;
/* if(InternetAvailable()){
//startAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("start address:"+startAddress);
}*/
}else{
endLocation = newLocation;
/*if(InternetAvailable()){
//endAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("endAddress :"+endAddress);
}*/
}
currentLocation = newLocation;
} catch (Exception e) {
currentLocation = newLocation;
e.printStackTrace();
}
}
public boolean InternetAvailable() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// while(isStopMe){
System.out.println("This is inside ................. :");
try {
if (!checkConnection()) {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("First");
} else {
if (inetAddr()) {
System.out.println("Net Connectivity is Present");
isInternet = true;
System.out.println("Second");
} else {
if (mobileConnect()) {
System.out.println("THIRD");
if (inetAddr()) {
System.out
.println("Net Connectivity is Present");
isInternet = true;
System.out.println("FOURTH");
} else {
System.out
.println("No Internet Connectivity");
isInternet = false;
System.out.println("FIFTH");
}
} else {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("SIX");
}
}
}
} catch (Exception ex) {
System.out.println("Leak ko catch");
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isInternet;
}
public boolean checkConnection() {
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
public boolean inetAddr() {
boolean x1 = false;
try {
Socket s = new Socket();
s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
InputStream is = s.getInputStream();
Scanner scan = new Scanner(is);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
x1 = true;
}
} catch (IOException e) {
x1 = false;
}
return x1;
}
public boolean mobileConnect() {
boolean conn = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNet != null) {
conn = true;
} else {
conn = false;
}
return conn;
}
#SuppressWarnings("deprecation")
private void myNotify(String text) {
Notification notif = new Notification(R.drawable.ic_launcher, text, System
.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
notif.setLatestEventInfo(this, "MotorVehicleApp", text, contentIntent);
// notif.defaults = Notification.DEFAULT_VIBRATE;
myNotificationManager.notify((int) System.currentTimeMillis(), notif);
}
#Override
public void onCreate() {
super.onCreate();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
intent = new Intent(BROADCAST_ACTION);
android.util.Log.d("MWD", "creating");
myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("location manager:"+myLocationManager.getAllProviders());
myLocationProvider = myLocationManager.getProvider("gps");
myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
updatePreferences();
handler.post(new Runnable() {
#Override public void run() {
Toast.makeText(getApplicationContext(), "Address:"+startAddress, Toast.LENGTH_LONG).show(); } });
}
public void updatePreferences() {
// sync local variables with preferences
android.util.Log.d("NWD", "updating preferences");
frequency = 10;
// update the LM with the new frequency
myLocationManager.removeUpdates(this);
myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
}
#Override
public void onDestroy() {
super.onDestroy();
/////------set edittext editable
android.util.Log.d("NWD", "destroying");
System.out.println("Inside on destroy of MWService");
myLocationManager.removeUpdates(this);
//myNotify("stopping");
InsertTripDetails_AsyncTask insert = new InsertTripDetails_AsyncTask();
insert.execute();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
handler.removeCallbacks(sendUpdatesToUI);
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
android.util.Log.d("NWD", "starting");
currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
//myNotify("starting");
handler.postDelayed(sendUpdatesToUI, 3000); // 1 sec
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
System.out.println("total_distance::"+total_distance);
intent.putExtra("distance",(total_distance/1000));
sendBroadcast(intent);
handler.postDelayed(this, 3000);
}
};
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public IBinder onBind(Intent arg0) {
return null; // this is for heavy IPC, not used
}
private class InsertTripDetails_AsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
try {
//InternetAvailable()
if(InternetAvailable()){
startAddress = geocoder.fetchCityName(getApplicationContext(),startLocation);
System.out.println("start address:"+startAddress);
endAddress = geocoder.fetchCityName(getApplicationContext(),endLocation);
System.out.println("end address:"+endAddress);
}else{
System.out.println("internet not available");
}
// Internet not available when data are store in latitude and longitute format
if(startAddress.equalsIgnoreCase("") && endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("1 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+",lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
}else if(startAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("2 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+","+endAddress);
}else if(endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
try {
System.out.println(startAddress+",3 lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
System.out.println(startAddress+" "+ endAddress);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("In catch of webservice thus no internet");
}
return "dfs";
}
#Override
protected void onPostExecute(String result) {
}
}
}
code for geocoder class
public class GeocoderHelper
{
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeocoderHelper.class.getName());
private String address="";
private Location i_Location;
private Context i_Context;
public String fetchCityName(final Context contex, final Location location)
{
i_Location = location;
i_Context = contex;
try {
return new Address().execute().get();
} catch (Exception e) {
return address;
}
}
public class Address extends AsyncTask<Void, Void, String>
{
#SuppressWarnings("unused")
#Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
System.out.println("location latitude is"+i_Location.getLatitude());
System.out.println("location longitude is"+i_Location.getLongitude());
Geocoder geocoder = new Geocoder(i_Context, Locale.getDefault());
List<android.location.Address> addresses = geocoder.getFromLocation(i_Location.getLatitude(), i_Location.getLongitude(), 1);
if (addresses.size() > 0)
{
//cityName = addresses.get(0).getLocality();
address = addresses.get(0).getLocality();
System.out.println("geocoder inside present address is"+address);
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
try
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + i_Location.getLatitude() + ","
+ i_Location.getLongitude() + "&sensor=false&language=fr";
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
address = result.getString("formatted_address");
System.out.println("map address:"+address);
break;
/* if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String ROUTE= null;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
address = cityName;
return cityName;
}
}
}
}*/
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return address;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
}
code for MAinActivity class
public class MainActivity extends Activity {
//private final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(MainActivity.this,MWService.class));
}
#Override
protected void onPause() {
super.onPause();
stopService(new Intent(MainActivity.this,MWService.class));
}
}
i have use permission in my menifest file for both internet and AccessFineLocation
my logcat msg.....
10-31 13:40:41.937: ERROR/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.address2/com.example.android.MainActivity}: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
10-31 13:40:41.937: ERROR/AndroidRuntime(825): Caused by: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
code for my menifest file....
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.android.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MWService"></service>
</application>

Categories

Resources