I want to find current location and compare it with some data in my database through a background service activity...but not getting any idea on how to do it...so please give me some advice...this is how I am doing currently
package com.example.alert;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
LocationListener ll = new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Reto Meier (Android Developer Relations) did a whole lot of work in this area, I suggest you check it out.
Blogged here http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Sample code here https://code.google.com/p/android-protips-location/
Related
I'm pretty new to android, and this is my first post here, so please be kind! :-)
I'm trying to create a service which runs in the background and does a location update every x minutes. To run it every x minutes I'm using the AlarmManager, as described here: Alarm Manager Example
Here's what I've got:
package com.example.service1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
public class Scheduler extends BroadcastReceiver{
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//Code which is executed every X seconds/minutes
getLocation(context);
//End of Code
wl.release();
}
public void setScheduler(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Scheduler.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 20, pi);
}
//Method to get the Location
public void getLocation(Context context) {
Log.e("null","getLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(null, "location change");
makeUseOfLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
};
}
//Method to work with the location Data; Instance of Point is created
public void makeUseOfLocation(Location location) {
Log.e(null,"makeuse");
Log.e(null,location.getLatitude() + "");
}
}
getLocation() is called every 20 seconds, but then it never runs onLocationChanged() (I use the EmulatorControl in Eclipse to change the location).
I had the same problem before when I used the ScheduledExecutorService instead of the AlarmManager.
Can anyone help me?
Looking at your code I never see the call to locationManager.requestLocationUpdates() with your listener as an argument.
This means that your listener is never registered with the location manager, and therefore does not get called.
You probably only want to register one listener, instead of registering a new one every time.
Try this..
protected void updateNotification() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener {
public void onLocationChanged(Location location){
if(location!=null){
if(location.hasAccuracy()){
dumpLocation(location);
}else{
dumpLocation(location);
}
}
}
public void onProviderDisabled(String provider){
Log.v("Loc Update","\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider){
Log.v("Loc Update","\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras){
Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
+ status + ", extras=" + extras);
}
I researched for this Nullpointer Exception. After googling i found most of them were due to null references to the UI elements. But mine does not have any. I just can't get the reason for the null pointer. I directly tested it on my android phone running 2.3.7. And yes, i added the permissions in the manifest file.
package com.GodTM.projectshoppers;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class HomeActivity extends Activity {
private ImageButton get;
private ImageView quit,settings;
private LocationManager locMan;
public LocationListener LocLis;
public Location currLoc;
private double[] passloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
get=(ImageButton)findViewById(R.id.homeGetButton);
settings = (ImageView)findViewById(R.id.homeSettingsButton);
quit = (ImageView)findViewById(R.id.homeExitButton);
Criteria crit=new Criteria();
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LocLis = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
}
};
//Criteria crit = new Criteria();
if(currLoc !=null){
passloc[0] = currLoc.getLatitude();
passloc[1] = currLoc.getLongitude();
Toast.makeText(getApplicationContext(), "Lat:" + currLoc.getLatitude() + "\nLong:" + currLoc.getLongitude(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Not Available", Toast.LENGTH_SHORT).show();
}
get.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(currLoc!=null){
Intent i = new Intent(HomeActivity.this, Screen2.class);
i.putExtra("Loc", passloc);
startActivity(i);
}
else{
Toast.makeText(getApplicationContext(), "Location Not Available", Toast.LENGTH_SHORT).show();
}
}
});
settings.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent j = new Intent(this, screen4.class);
// startActivity(j);
}
});
quit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onResume(){
super.onResume();
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER , 0, 0, LocLis);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
currLoc is never initalized. Since location and currLoc are both Location you can change
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
with
currLoc = location;
You didn't initialize passLoc. And you call getLastKnownLocation without saving the location itself.
So i am just trying to get location of user and show it in a toast...but its not working at all...i also tried just to show toast when activity starts but it is not working even at that time
Here's my code
package com.example.alert;
import com.example.alert.CurrentLocation.MyLocationListener;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ViewAlerters extends Activity{
private Button addButton;
private Button removeButton;
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_alerters);
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
setUpViews();
}
private void setUpViews() {
Toast.makeText( getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
addButton = (Button) findViewById(R.id.add_button);
//alerterText = (TextView) findViewById(R.id.alert_list_text);
removeButton = (Button)findViewById(R.id.remove_button);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ViewAlerters.this,AddAlerter.class);
startActivity(intent);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
}
Don't use getApplicationContext:
Toast.makeText( this,"Hello",Toast.LENGTH_SHORT).show();
Refer to this question about the differences in the Contexts: difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();
I have created one service and also added it in manifest. When I use timer to call this service periodically and in timer I have used location manager to get location of user contin. But there is error like that:
05-11 11:57:17.574:
ERROR/AndroidRuntime(3305):
java.lang.RuntimeException: Can't
create handler inside thread that has
not called Looper.prepare()
Tell me where is problem in my code.
code is here
package com.collabera.labs.sai;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class SimpleService extends Service {
Timer mytimer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
mytimer = new Timer();
mytimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//getdata();
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
}
},0,1000);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
public void getdata()
{
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitude = "
+ loc.getLatitude() + "Longitude = " + loc.getLongitude();
/*Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)
.show();*/
Log.d("TAG", "Starting..");
}
#Override
public void onProviderDisabled(String provider) {
/*Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();*/
}
#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) {
}
}/* End of Class MyLocationListener */
}
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
You can't modify UI from the non-UI thread. Services are never executed on the UI thread. Log this instead of making a Toast.
I am looking for the optimized way to get user's location and I found the sample example here, which was answered by Mr. Fedor on on Jun 30 '10
I did the same way as he explained in his code, the only difference is that I am using the gotLocation callback method of abstract class result. In this method I am tring to show the Provider name as a msg using Toast.makeText. When I run this code, nothing get displayed on my emulator and after few seconds it show the message "Application has stopped unexpectedly android emulator". I increase the time, which was set in the timer1.schedule method, but no luck.
I am just stating development in android platform, so I don't have enough knowledge about the same, so can anybody help me to resolve this issue.
Below is my code
file Name: UserLocation.java
package com.ideafarms.android.mylocation;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class UserLocation{
Timer timer1;
LocationManager locMgr;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerNetwork);
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerGps);
}
};
public boolean getLocation(Context context, LocationResult result){
// Use LocationResult callback class to pass location value from UserLocation to User code
locationResult = result;
if(locMgr == null){
locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Handle exception if provider is not permitted
try{
gps_enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
// don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled){
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
return true;
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
locMgr.removeUpdates(locationListenerGps);
locMgr.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled){
gps_loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled){
net_loc=locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
// if there are both values use the latest one
if(gps_loc!=null && net_loc!= null){
if(gps_loc.getTime()>net_loc.getTime()){
locationResult.gotLocation(gps_loc);
}else{
locationResult.gotLocation(net_loc);
}
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
and
package com.ideafarms.android.mylocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.ideafarms.android.mylocation.UserLocation.LocationResult;
public class MyLocation extends Activity {
/** Called when the activity is first created. */
TextView myLoc ;
public LocationResult locResult = new LocationResult(){
#Override
*public void gotLocation(Location location) {
// TODO Auto-generated method stub
Toast msg = Toast.makeText(MyLocation.this, location.getProvider(), Toast.LENGTH_LONG);
//msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}*
};
boolean loc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
UserLocation usrLocation = new UserLocation();
myLoc = (TextView)findViewById(R.id.myLocation);
loc = usrLocation.getLocation(this, locResult);
}
}
I have marked the code in italic where I am having problem.
Thanks
Take a look here: http://developer.android.com/guide/developing/tools/emulator.html
You need to emulate an gps device in order to get location data from the emulator.