简体   繁体   中英

Android : Make application wait till the current location is found

I'm trying to make my app wait till the current location is found. I've tried few different ways using Threads and all have failed really. I was using wait() and notify() but application just hung and never found the current location.

I amen't using google map api as it is not part of the application. Does anyone have any ideas how to do this or examples.

EDIT : The Thread I was using did not start till the user pressed a button then within onLocationChanged other data is processed eg adding the new location to ArrayList, Calculate the distance between the current and last Location as well as the Time taken to get to the new location

You could try starting an AsyncTask in onCreate to get the location. Your default onCreate layout could be a "loading" page, then when your AsyncTask completes successfully with the location it draws your "real" UI.

So if I understand what you want to do correctly, then I would avoid making another thread in onClick() . Instead, onClick() should just request a location, display a progress dialog, and return. Since the work you want to do happens after you receive the new location, I would start an AsyncTask there. Then you finally remove the dialog box (removing it returns control to the user) when the AsyncTask finishes.

Code usually helps, so, I would put this in onCreate() or wherever:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        listener.refresh();
    }
});

And put this in your LocationListener:

public void refresh() {
    myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    myDialog = new ProgressDialog(myContext);
    myDialog.setIndeterminate(true);
    myDialog.show();
}

@Override
public void onLocationChanged(Location location) {
    // now do work with your location, 
    // which your probably want to do in a different thread
    new MyAsyncTask().execute(new Location[] { location });
}

And then you need an AsyncTask, which may look like this:

class MyAsyncTask extends AsyncTask<Location, Void, Void> {
    @Override
    protected Void doInBackground(Location... location) {
        // start doing your distance/directions/etc work here
        return null;
    }


    @Override
    protected void onPostExecute(Void v) {
        // this gets called automatically when you're done, 
        // so release the dialog box
        myDialog.dismiss();
        myDialog = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM