由于获取GPS /地理位置,主UI挂起

时间:2013-06-28 18:52:42

标签: android geolocation android-asynctask

我试图在应用程序启动时获取用户的GPS / GeoLocation,但有时它会导致应用程序UI不响应,然后着名的Android提示应用程序没有响应!所以我决定尝试使用AsyncTask来获取用户在主活动中的位置信息;但有时UI仍会挂起(通常当gps设置被禁用时,所以我进入系统设置启用它,当我按回来返回我的应用程序时,它变得如此缓慢/无响应。)所以我在这里做错了什么? 任何帮助表示赞赏。

我的网络课应该获取位置信息:

package com.parspake.kookojapost;

import android.content.Context;
import android.location.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class ConnectionHandler {

private Context ctx;
double mLat;
double mLong;
String currCity;
String currCountry;
String mAddress;
LocationManager currentLoc;
LocationListener locLis;

public ConnectionHandler(Context context) {
    this.ctx = context;
}

public boolean internetAccess() {
    ConnectivityManager con = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = con.getActiveNetworkInfo();
    // Simplified: return netInfo != null && netInfo.isConnected();
    if (netInfo != null && netInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

public boolean locationSourceEnabled() {
    currentLoc = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    boolean isInternetLocationAvailable = currentLoc.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    boolean isGpsAvailable = currentLoc.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (isInternetLocationAvailable) {
        Log.d("kookojaPost", "internet location avaiable");
        return true;
    } else if (isGpsAvailable) {
        Log.d("kookojaPost", "gps location avaiable");
        return true;
    }
    return false;
}

public void getLocation() {

    locLis = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {


            Geocoder gcd = new Geocoder(ctx, Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                if (addresses.size() > 0) {
                    currCity = addresses.get(0).getLocality();
                    currCountry =  addresses.get(0).getCountryName();
                    mAddress = currCity + " - " + currCountry;
                }
            } catch (IOException e) {
//                    e.printStackTrace();
                    Log.d("kookojaPost", e.getMessage());
                }
                String s = "Loction: \n" + mAddress;
            Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
            Toast.makeText(ctx, "Location GPS: " + location.getLatitude() + " - " + location.getLongitude(), Toast.LENGTH_LONG).show();
            mLat = location.getLatitude();
            mLong = location.getLongitude();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
        }
    };

    currentLoc = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    if (locationSourceEnabled()) {
        if (currentLoc.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            currentLoc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 50, locLis, Looper.getMainLooper());
        }
        if (currentLoc.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            currentLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 50, locLis, Looper.getMainLooper());
        }
    }
 }
}

这是我的主要活动,我在这里使用AsyncTask做背景材料,显然没有做它应该做的事情!

package com.parspake.kookojapost;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;

public class MainAct extends Activity {

ProgressBar pg;
ConnectionHandler mNet;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    pg = (ProgressBar) findViewById(R.id.progressBar);
    mNet = new ConnectionHandler(this);

//        pg.setIndeterminate(true);
//        pg.setVisibility(View.VISIBLE);


//        new FetchLocation().execute();

}

@Override
protected void onResume() {
    super.onResume();

    new FetchLocation().execute();

}


private class FetchLocation extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pg.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        if (mNet.locationSourceEnabled()) {
            Log.d("kookojaPost","mLat is: " + mNet.mLat);
//               while (mNet.mLat == 0.0) {
//                   mNet.getLocation();
//               }
            if (mNet.mLat == 0.0) {
                mNet.getLocation();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        pg.setVisibility(View.INVISIBLE);
    }
 }
}

1 个答案:

答案 0 :(得分:2)

我使用此代码而不使用AsyncTask:

希望它对其他人有用。

    Runnable runThis = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            if (mNet.locationSourceEnabled()) {
                mNet.getLocation();
            }
            Looper.loop();
        }
    };

    Thread th = new Thread(runThis);
    th.start();