Accessing GPS using AsyncTask - android

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));
}
}
}`

Related

android getContentResolver() order issue

project structure
I am trying to getContentResolver in MyLocationListenerActivity for accessing the data base which is implemented as LogContentProvider here. I have registered the MyLocationListenerActivity to the locationManager in MainActivity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void trackingServiceButtonOnClick(View v) {
startActivity(new Intent(MainActivity.this,
MyLocationListenerActivity.class));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListenerActivity myLocationListener = new MyLocationListenerActivity();
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener);
} catch (SecurityException e) {
Log.d("debug", e.toString());
}
if (getContentResolver() != null) {
Log.d("debug", "I can get content resolver");
}
}
and in MyLocationListenerActivity, If I want to getContentResolver() in onCreate(), that's fine, but If I try to getContentResolver in onLocationChanged, a error "get contentResolver() on a null object reference occurs", does anyone know why this happens?
public class MyLocationListenerActivity extends AppCompatActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_listener);
// test() works fine here
test();
}
public void test() {
getContentResolver();
}
#Override
public void onLocationChanged(Location location) {
// error will happen here
test();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}

running an script only for an specific time

I have a code for detecting location that I want to works only for 2 minutes.
when I fire start() method script must works almost for 2 minutes.
problem is in there that how run my script only for an specific time.
I used this code but don't running correct.
don't fire stop() method from in Timer().schedule()
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
new Timer().schedule(
new TimerTask(){
public void run() {
stop();
}
}
,System.currentTimeMillis(), 2*60*1000);
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
lastloc = location;
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
Check your code of Timer again. Usually, the Timer code should be like:
Timer.schedule(TimerTask,
delayTime); // delay a task before executed for the first time, in milliseconds
Because of your delayTime has been executed by using System.currentTimeMillis(), the System picks the current time in milliseconds since midnight, so that the TimerTask will be executed after millions millisecond.
Hence, use this code:
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// do your thing here
}
}, 2*60*1000);
See this documentation about the type of Timer you created.
I finally solved my problem by using handlers.
read this page: Using Bundle Android to Exchange Data Between Threads
a.java
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
private Thread workingthread = null;
final Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
Log.d("states","return msg from timer2min");
if(msg.what==1){
stop();
}
super.handleMessage(msg);
}
};
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
workingthread=new timer2min(mHandler);
workingthread.start();
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
timer2min.java
public class timer2min extends Thread {
private Handler hd;
public timer2min(Handler msgHandler){
hd = msgHandler;
}
public void run() {
try {
Thread.sleep(2*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = hd.obtainMessage();
msg.what = 1;
hd.sendMessage(msg);
}
}

turn on gps and using it

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();

Multiple onResume() when coming back to my activity from Home

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);
}
}

How to return data in Android LocationListener

i want to build an app in which users can make foto which is tagged with the current location of the phone. So after making a foto, the user can save the picture by touching on the "save" button. If the button is touched the current location will be determined with my own LocationListener class. The Listener-class shows a Progressdialog and dismiss it, after a location is found. But now i want to know which i can return the location back to the calling Activity, because the Location listener methods are callback methods. Is there a "best-practice" solution for that, or have anybody a clue?
Location Listener:
public class MyLocationListener implements LocationListener {
private ProgressDialog progressDialog;
private Context mContext;
private LocationManager locationManager;
public MyLocationListener(Context context, ProgressDialog dialog) {
mContext = context;
progressDialog = dialog;
}
public void startTracking() {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 10, 10, this);
progressDialog.show();
}
private void finishTracking(Location location) {
if(location != null) {
locationManager.removeUpdates(this);
progressDialog.hide();
Log.i("TRACKING",location.toString());
}
}
#Override
public void onLocationChanged(Location location) {
finishTracking(location);
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
Calling code:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Determine position...");
new MyLocationListener(this, dialog).startTracking();
Why not pass your own callback from activity to MyLocationListener and call its method from finishTracking?
Its a commonly used delegation pattern. Something like that:
class MyLocationListener implements LocationListener {
public interface MyListener {
void onLocationReceiver( Location location );
}
private MyListener listener;
public MyLocationListener(Context context, ProgressDialog dialog, MyListener listener) {
mContext = context;
progressDialog = dialog;
this.listener = listener;
}
private void finishTracking(Location location) {
if(location != null) {
locationManager.removeUpdates(this);
progressDialog.hide();
Log.i("TRACKING",location.toString());
listener.onLocationReceiver(location);
}
}
}
and call:
new MyLocationListener(this, dialog, new MyLocationListener.MyListener() {
public void onLocationReceived( Location location ) {
text.setText(location.toString());
}
}).startTracking();
You can do another simple thing - put your class MyLocationListener inside your Activity itself and modify the field in your activity inside your MyLocationListener itself.

Categories

Resources