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;
}
}
}
}
Related
I'm a bit new to Android and I'm trying to move some location finding and volley methods out of my fragment into a service, but now sure where to put what. It's basically a weather app that gets your current location and uses volley to pull forecast.io api data.
Here is my fragment now:
public class WeatherListFragment extends ListFragment implements LocationListener {
private final String initialURL = "https://api.forecast.io/forecast/8fc2b0556e166fa4670d4014d318152a/";
Weather[] myWeatherArray = {};
Weather myWeatherObject;
WeatherAdapter weatherAdapter;
LocationManager mLocationManager;
String currentLoc;
JSONArray data;
JSONObject day;
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
// Remove the listener you previously added
mLocationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
makeUseOfNewLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
}
public void getData() {
String API_URL = setLatLong(initialURL, currentLoc);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, API_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject daily = response.getJSONObject("daily");
data = daily.getJSONArray("data");
myWeatherArray = new Weather[data.length()];
for (int i = 0; i < myWeatherArray.length; i++) {
day = data.getJSONObject(i);
myWeatherObject = new Weather();
myWeatherObject.setmDate(day.getInt("time"));
myWeatherObject.setmTempMin(day.getInt("temperatureMin"));
myWeatherObject.setmTempMax(day.getInt("temperatureMax"));
myWeatherObject.setIcon(day.getString("icon"));
myWeatherArray[i] = myWeatherObject;
}
} catch (JSONException e) {
e.printStackTrace();
}
if (weatherAdapter != null) {
weatherAdapter.setData(myWeatherArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "volley died", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void makeUseOfNewLocation(Location location) {
if (location == null) {
return;
}
mLocationManager.removeUpdates(this);
double latDouble = location.getLatitude();
double longDouble = location.getLongitude();
String latString = String.valueOf(latDouble);
String longString = String.valueOf(longDouble);
String latLong = latString + "," + longString;
Log.e("gps", latLong);
currentLoc = latLong;
getData();
}
public String setLatLong(String roughURL, String loc) {
return roughURL + loc;
}
and here is the blank Service class using a Handler:
public class NotificationService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Notification n = new Notification(getApplicationContext());
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Thread.MIN_PRIORITY);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
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>
Have the next problem, need a program to send the coordinates any hour to my server. Im create a taskmanager and can send the coordinates, buy only Work the first three or five times and died.
This is my code please how is my problem?
My MainActivity:
public class MainActivity extends Activity {
public int ingreso =0;
double latitud=0;
double longitud=0;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public double lat1=0;
public double lon1=0;enter code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final InstallationId Miid = new InstallationId();
Alarmas mUIUpdater = new Alarmas(new Runnable() {
#Override
public void run() {
// do stuff ...
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
isGPSEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled )
{
/*NO HAY GPS*/
Toast.makeText( getApplicationContext(),"El GPS se encuentra desactivado. Favor activarlo para determinar el Centro de embellecimiento mas cercano",Toast.LENGTH_LONG ).show();
Intent intentRedirectionGPSSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intentRedirectionGPSSettings.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intentRedirectionGPSSettings, 0);
}
else
{
if (isGPSEnabled)
{
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
else
{
if (isNetworkEnabled)
{
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
}
}
}
lat1=((MyLocationListener) mlocListener).GetLatitud();
Log.d("Enviando datos", "es " + ((MyLocationListener) mlocListener).GetLatitud());
lon1=((MyLocationListener) mlocListener).GetLongitud();
String miurl="http://casoft.com.co/evvc/registro.php?idphone=" + Miid.id(getApplicationContext()) + "&lat1=" + lat1 + "&lon1=" + lon1;
new Tareas().execute(miurl);
mlocManager.removeUpdates(mlocListener);
}
});
mUIUpdater.startUpdates();
//new Tareas().execute("http://casoft.com.co/evvc/registro.php?idphone=1&lat1=1&lon1=2");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitud = loc.getLatitude();
longitud= loc.getLongitude();
Log.d("Enviando datos", latitud + "es " + longitud);
}
#Override
public void onProviderDisabled(String provider)
{
ingreso=0;
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public double GetLatitud()
{
return latitud;
}
public double GetLongitud()
{
return longitud;
}
}/* End of Class MyLocationListener */
public void Sael(View view) {
Intent i = new Intent(this, navegador.class );
startActivity(i);
}
}
This is to get the idphone:
public class InstallationId {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
And this is the Alarm:
public class Alarmas {
private Handler mHandler = new Handler(); // TODO Don't know if this is created in the UI thread
private Runnable mStatusChecker;
private int UPDATE_INTERVAL = 9000;
/**
* Creates an UIUpdater object, that can be used to
* perform UIUpdates on a specified time interval.
*
* #param uiUpdater A runnable containing the update routine.
*/
public Alarmas(final Runnable uiUpdater){
mStatusChecker = new Runnable() {
#Override
public void run() {
// Run the passed runnable
uiUpdater.run();
// Re-run it after the update interval
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
/**
* The same as the default constructor, but specifying the
* intended update interval.
*
* #param uiUpdater A runnable containing the update routine.
* #param interval The interval over which the routine
* should run (milliseconds).
*/
public Alarmas(Runnable uiUpdater, int interval){
this(uiUpdater);
UPDATE_INTERVAL = interval;
}
/**
* Starts the periodical update routine (mStatusChecker
* adds the callback to the handler).
*/
public void startUpdates(){
mStatusChecker.run();
}
/**
* Stops the periodical update routine from running,
* by removing the callback.
*/
public void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}
}
And this is the TASK
class Tareas extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
Log.d("Enviando datos", "Solicitando");
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
Thanks for your help.
Pda: Im need this program Work all time and only send me the GPS report any hour, for testing have the UPDATE_INTERVAL any 9 seconds.
buy only Work the first three or five times and died.
That would be because Android terminated your process, in all likelihood.
Please use AlarmManager for work that should occur once an hour. Getting a location fix once per hour is a bit tricky -- I have a LocationPoller library that can help with that.
Today i made my first background service that keeps running if i exit from my application.
It is logging lattitude and londitude.
I would like to add some more functions to my code, and i would like to ask your help about which way should i contine coding, and is it good that i made already?
I work with an Activity, with a handler that gets messages from background service:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_act);
BackgroundLocationService.context=this;
Intent i = new Intent(this, BackgroundLocationService.class);
i.putExtra("handler", new Messenger(this.handler));
startService(i);
/*.......more code here......*/
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// get data from msg
String result = msg.getData().getString("result");
Log.i("Activiti map: Locationing Service handler: ",
"get data: " + result);
super.handleMessage(msg);
}
};
And this is my background service:
public class BackgroundLocationService extends IntentService {
private static final String TAG = "Activiti map: Locationing Service";
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
public static Context context;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private boolean DEBUG=false;
private String latitude="0";
private String londitude="0";
Messenger messenger;
Timer t=new Timer();
public BackgroundLocationService()
{
super("myintentservice");
locManager = (LocationManager) context.getSystemService
(Context.LOCATION_SERVICE);
try {
gps_enabled =
locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
if(DEBUG)
Log.e(TAG, ex.toString());
}
try {
network_enabled =
locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
if(DEBUG)
Log.e(TAG, ex.toString());
}
if (gps_enabled) {
if(DEBUG)
Log.i(TAG, "Gps is Enabled!");
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locListener);
} else {
if(DEBUG)
Log.i(TAG, "Gps is Disabled!");
}
if (network_enabled) {
if(DEBUG)
Log.i(TAG, "Network provider is enabled!");
locManager.requestLocationUpdates
(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
} else {
if(DEBUG)
Log.i(TAG, "Network provider is Disabled!");
}
}
#Override
protected void onHandleIntent(Intent intent) {
messenger=(Messenger) intent.getExtras().get("handler");
t.schedule(new TimerTask() {
#Override
public void run() {
// just call the handler every 3 Seconds
Message msg=Message.obtain();
Bundle data=new Bundle();
data.putString("result", "latitude: " + latitude+
" londitude: "+londitude);
msg.setData(data);
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 100,3000);
}
class MyLocationListener implements LocationListener {
private static final String TAG = "Activiti map: LocationListener";
public void onLocationChanged(Location location) {
if (location != null) {
locManager.removeUpdates(locListener);
londitude = Double.toString(location.getLongitude());
latitude = Double.toString(location.getLatitude());
if(DEBUG)
Log.i(TAG, "Londitude: " + londitude + " Latitude: " + latitude);
}
}
public void onProviderDisabled(String arg) {
if(DEBUG)
Log.i(TAG, "Provider just Disabled: " + arg);
}
public void onProviderEnabled(String arg) {
if(DEBUG)
Log.i(TAG, "Provider just Enabled: " + arg);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Some problems that i would like to solve:
Is it possible to control the handler the service or anything in my code to keep SURE, that the service is stopped, started, etc? So i would like to add controls for example from a widget button for turning on and off the service. How is it possible ?
And another thing: If i quickly starts and exit my application many times i got each time a handler initalized and i got multiple log messages. How can i make a singleton of this or something like that?
Thanks for helping
Use Application for those purposes.
You can implement singleton logic into Application class and manage your service.
If you close your activity, the Service asks Application if Activity alive.
On Launch Activity, Application knows about and Service can bind with above mentioned Activity by using some Interfaces that Application stores.
**
The main Activity must initiate Handler to make to Service to talk with Activity
Here is some code:
public class MyApplication extends Application{
private static MyApplication mSingleton;
private static final String PACKAGE = "com.code";
private static final String PROCESS_NAME = PACKAGE + ".ui";
private static final String SERVICE_NAME = PROCESS_NAME + "/" + PACKAGE + ".srvce.MyService";
#Override
public void onCreate() {
super.onCreate();
mSingleton = this;
}
public MyApplication getApp(){
return mSingleton;
}
....
public boolean isServiceRun() {
ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
boolean isRunnig = false;
for (int i = 0; i < services.size(); i++) {
RunningServiceInfo inf = services.get(i);
if(PROCESS_NAME.equals(inf.process)){
ComponentName cn = inf.service;
String str = cn.toString();
if(str.contains(SERVICE_NAME)){
isRunnig = true;
return isRunnig;
}
}
}
return isRunnig;
}
}
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;
}
}