When I am navigating out from my (main) activity and then coming back by clicking the icon on the Home screen - the activity is automatically Resumed->Paused->Resumed.
I am expecting for only one onResume().
My activity creates an AsyncTask in the onResume() function (the activity is not calling to other activities at all) and currently two additional AsyncTasks are created instead of one.
I did some tests and noticed that it happens when this activity is declared as "SingleTask" in the Mainfest. With 'SingleTop" it goes fine and onResume() is called only once.
HELP!
This is my code of the main activity:
public class HomeFinderActivity extends ListActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private Location location;
private static final String LOG_TAG = "::HomeFinderActivity->Asynctask";
private ArrayList<Home> home_parts = new ArrayList<Home>();
private ListViewAdapter m_adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// instantiate ListViewAdapter class
m_adapter = new ListViewAdapter(this, R.layout.row, home_parts);
setListAdapter(m_adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
}
//Asynctask to retrieve cursor from database and sort list by distance
private class SortList extends AsyncTask<Location, Void, ArrayList<Home>> {
#Override
protected ArrayList<Home> doInBackground(Location... location) {
try {
if (home_parts.isEmpty()){
home_parts=Home.getHomeParts(location[0], getApplicationContext());
}
else{
for (Home d : home_parts){
if (location != null){
d.setmDistance((int) (d.getmLatitude()), d.getmLongitude(),(double) (location[0].getLatitude())
, (double) (location[0].getLongitude()));
}
}
}
} finally {
}
Collections.sort(home_parts, new Comparator(){
public int compare(Object o1, Object o2) {
Home p1 = (Home) o1;
Home p2 = (Home) o2;
return (int) p1.getmDistance()- (int) p2.getmDistance();
}
});
return home_parts;
}
protected void onPostExecute(ArrayList<Home> address) {
m_adapter = new ListViewAdapter(HomeFinderActivity.this, R.layout.row, address);
// display the list.
setListAdapter(m_adapter);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
//starting handling location
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
Log.e(LOG_TAG, "onResume() started");
if (location != null) {
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
Log.e(LOG_TAG, "onPause() started");
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
SortList showList = new SortList();
showList.execute(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
/** Called when the user clicks the Add Entry button */
public void goAddEntry(View view) {
Intent intent = new Intent(this, AddEntry.class);
startActivity(intent);
}
}
Related
Here is what I need to do. I need to launch my application and on the click of a button, I need to display the current coordinates, that is latitude and longitude. I followed this tutorial and used the following code for my purpose:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#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
}
}
(Copy pasted only a part of the code, please ignore any unclosed brackets or anything like that.)
It continuously gets the latitude longitude as location changes and stores it to two double variables latitude and longitude and when the setButton is clicked, it displays the last stored lat-lon value. That would be the user's current location. Now the issue is, I launched the app and while still staying on the exact location from which the app is launched, I clicked the Set Button. But at that time the location is not changed, so the latitude and longitude are displayed as zero, which is the default value of the double variables. I need to take a walk around with the device so that the location is changed before I can get my actual coordinates. How can I get the lat-lon as soon as the app is launched?
You can use getLastKnownLocation(...) to initialise the longitude and latitude values like this:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
This is your total class.
public class MainActivity extends Activity {
public double latitude;
public double longitude;
private TextView latValueLabel,lonValueLabel ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
latValueLabel = (TextView)findViewById(R.id.latLabel);
lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
I have a class for get the user location.
If the GPS is off I turned it on and show the location, but it doesnt work.
this is the class:
public class UseGPS implements Runnable{
Activity activity;
Context context;
private ProgressDialog pd;
LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
public UseGPS(Activity Activity, Context Context){
this.activity = Activity;
this.context = Context;
}
public void getMyPos(){
DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity,"no gps signal",Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
}
};
pd = ProgressDialog.show(activity,context.getString(R.string.looking_for), context.getString(R.string.gps_signal), true, true, dialogCancel);
writeSignalGPS();
}
private void setCurrentLocation(Location loc) {
currentLocation = loc;
}
private void writeSignalGPS() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
mLocationManager.removeUpdates(mLocationListener);
if (currentLocation!=null) {
Toast.makeText(activity,currentLocation.getLatitude(),Toast.LENGTH_LONG).show();
Toast.makeText(activity,currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}
};
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
setCurrentLocation(loc);
handler.sendEmptyMessage(0);
}
}
#Override
public void onProviderDisabled(String provider) {
/*turn on GPS*/
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
}
#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
}
}
}
The code works when the GPS is turned on, but it doesnt turn the gps on.
What can I do?
While launching time of your app, give one pop-up message with option to turn on the GPS by the user.
This pop-up button navigates to GPS setting in Setting for their user can turn on the GPS.
Here is the code snippet:
AlertDialog gpsonBuilder = new AlertDialog.Builder(Home_Activity.this);
gpsonBuilder.setTitle("Your Gps Provider is disabled please Enable it");
gpsonBuilder.setPositiveButton("ON",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
gpsonBuilder.show();
I have a listview and onItemSelected, will call an Activity to get user location (his current lat and lng), this activity has no layout, then this activity automatically calls another activity which gets lat and lng of the item selected from the listview and marks both the user location and item location on the map.
This worked fine when I was testing on Emulator and Samsung Galaxy Ace, But it crashes when I'm testing on Micromax A50 and Sony Xperia.
Sad thing is that I can't install drivers of the later 2 devices, so I cant get logcat.
Can any 1 guess what might have gone wrong??
My code for finding user location is:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
/*Intent intent = new Intent(MyLocationActivity.this, ShowMapActivity.class);
startActivity(intent);*/
Intent intent = new Intent(MyLocationActivity.this, MapMarkerActivity.class);
startActivity(intent);
finish();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// 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
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
and item location is:
public class MapMarkerActivity extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
private Drawable marker1;
private Drawable marker2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular_entry);
Button feedButton = (Button) findViewById(R.id.feedButton_particularEntry);
feedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MapMarkerActivity.this,
FeedListViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
Button iWantButton = (Button) findViewById(R.id.iWantButton_particularEntry);
iWantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
IWantActivity.class);
startActivity(intent);
}
});
Button shareButton = (Button) findViewById(R.id.shareButton_particularEntry);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ShareActivity.class);
startActivity(intent);
}
});
Button profileButton = (Button) findViewById(R.id.profileButton_particularEntry);
profileButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ProfileActivity.class);
startActivity(intent);
}
});
map = (MapView) findViewById(R.id.map);
map.getController().setCenter(
getPoint(FeedListViewActivity.lat, FeedListViewActivity.lng));
map.getController().setZoom(13);
map.setBuiltInZoomControls(true);
marker1 = getResources().getDrawable(R.drawable.marker2);
marker2 = getResources().getDrawable(R.drawable.marker1);
marker1.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
marker2.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker1));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return (true);
} else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return (true);
}
return (super.onKeyDown(keyCode, event));
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
public class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
boundCenterBottom(marker);
OverlayItem oli1 = new OverlayItem(getPoint(
MyLocationActivity.myLocationLatitude,
MyLocationActivity.myLocationLongitude), "YL",
"Your Location");
oli1.setMarker(marker2);
items.add(oli1);
OverlayItem oli2 = new OverlayItem(getPoint(
FeedListViewActivity.lat, FeedListViewActivity.lng), "SL",
"Store Location");
oli2.setMarker(marker1);
items.add(oli2);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(MapMarkerActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}
Maybe this can help you:
Location Method Calls Crashes On Some Devices
Simply, I want to get current location and location changes through GPS via AsyncTask.
I have tried many ways out and also gone through many stuff related it, but cant help myself out. Here is my code, please suggest changes to make to the code.
public class MyGps extends Activity {
/** Called when the activity is first created. */
public static EditText txtLatitude;
public static EditText txtLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GpsAsyncTask gpsTask = new GpsAsyncTask(this, this);
gpsTask.execute(null);
}
}
public class GpsAsyncTask extends AsyncTask<String[], String, String> {
Context context;
Activity activity;
private LocationManager locationManager;
private Location currentLocation;
Double mlat, mlng;
public GpsAsyncTask(Activity act, Context ctx) {
context = ctx;
activity = act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
String provider = Settings.Secure.getString (context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
Toast.makeText(context, "Trying to connect GPS", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is not connected", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String[]... params) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0f, new LocationListener()
{
public void onLocationChanged(Location loc)
{
mlat=loc.getLatitude();
mlng=loc.getLongitude();
return;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
{
MyGps.txtLatitude.setText(Double.toString(mlat));
MyGps.txtLongitude.setText(Double.toString(mlng));
}
}
}`
I've got a location service to have an updated location in my app. I bind it to every activity requiring location data, and now I'd like to know in these activities when the location listener in the service receives events such as onLocationChanged, onProviderEnabled... How can I do that?
In my activities
private ServiceConnection mConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bind location service
bindService(new Intent(this, LocationService.class), mConnection, Context.BIND_AUTO_CREATE);
// Activity stuff...
}
#Override
protected void onDestroy() {
super.onDestroy();
// Unbind LocationService
context.unbindService(mConnection);
}
LocationService.java
public class LocationService extends Service implements LocationListener {
LocationManager locationManager;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
// Update after minimum 5 minutes and if user has moved at least 100 meters.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, this);
Location loc = getBestLocation(locationManager);
if(loc!=null){
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
}
}
public void onLocationChanged(Location loc) {
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
public static Location getBestLocation(LocationManager locationManager) {
Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If both are available, get the most recent
if(location_gps!=null && location_network !=null) {
return (location_gps.getTime() > location_network.getTime())?location_gps:location_network;
}
else if(location_gps==null && location_network ==null){
return null;
}
else
return (location_gps==null)?location_network:location_gps;
}
public void onProviderEnabled(String s){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 0, this);
}
public void onProviderDisabled(String s){
locationManager.removeUpdates(this);
GlobalVars.lat = null;
GlobalVars.lng = null;
}
public void onStatusChanged(String s, int i, Bundle b){}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
}
I would do it on this way:
Create LocationListener class..
Each time i get a new location, send broadcast message with specific predefined ACTION and in extras put lat and lon.
Each activity creates broadcast listener for this message with intentFilter(Action);
Get extras from the intent.