使用AsyncTask获取位置信息

时间:2014-02-01 22:59:28

标签: android android-asynctask location

我正在尝试使用反向地理编码来获取用户的当前位置坐标和地址。 由于此过程需要一些时间,我想在此期间显示进度条,因此我使用的是AsyncTask。所以,基本上我正在做的是,从一个活动的onClick事件开始,我启动AsyncTask,它找到位置信息,然后从AsyncTask开始另一个使用该信息的活动。

这是我的第一个活动,其中onClick事件启动AsyncTask:

public void onClickGirl(View view)
{
  (new MyAsyncTask(MainActivity.this)).execute();
}

这是AsyncTask:

public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
  private Context ContextAsync;
  public MyAsyncTask (Context context){
    this.ContextAsync = context.getApplicationContext();
  }

  Dialog progress;
  private String providerAsync;
  private LocationManager locationManagerAsync;  
  double   latAsync=0.0;
  double lonAsync=0.0;
  String thikanaAsync="Scan sms for location";

  String AddressAsync="";
  Geocoder GeocoderAsync;

  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    progress = ProgressDialog.show(null, "Loading data", "Please wait...");

  }

  @Override
  protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
    locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setCostAllowed(false);
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    providerAsync = locationManagerAsync.getBestProvider(criteria, false);

    if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      providerAsync = LocationManager.GPS_PROVIDER;
    } else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
      providerAsync = LocationManager.NETWORK_PROVIDER;
      /*AlertDialog.Builder alert = new AlertDialog.Builder(this);
      alert.setTitle("GPS is disabled in the settings!");
      alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
      alert.setPositiveButton("OK", null);
      alert.show();*/     
    } else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
      providerAsync = LocationManager.PASSIVE_PROVIDER;
      Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
    }    

    Location location = locationManagerAsync.getLastKnownLocation(providerAsync);
    // Initialize the location fields
    if (location != null) {
      //  System.out.println("Provider " + provider + " has been selected.");
      latAsync = location.getLatitude();
      lonAsync = location.getLongitude();
      onLocationChanged(location);
    } else {
      Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
    }

    List<Address> addresses = null;
    GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
    try {
       addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);

       String address = addresses.get(0).getAddressLine(0);
       String city = addresses.get(0).getAddressLine(1);
       String country = addresses.get(0).getCountryName();
       AddressAsync = Html.fromHtml(
               address + ", " + city + ",<br>" + country).toString();
    } catch (Exception e) {
       e.printStackTrace();
       AddressAsync = "Refresh for the address";
    }

    return null;
  }

  @Override
  protected void onPostExecute(Void result) {  

  super.onPostExecute(result);
  progress.dismiss();
  Intent intentAsync = new Intent(ContextAsync,Emerg.class);
    intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intentAsync.putExtra("calculated_Lat", latAsync);
    intentAsync.putExtra("calculated_Lon", lonAsync);
    intentAsync.putExtra("calculated_address", AddressAsync);
    ContextAsync.startActivity(intentAsync);  
  }

  @Override
  public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
      locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
  }

  @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

  }

}

这是在AsyncTask之后运行的第二个活动:`

Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");

这是LogCat:

02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.view.View$1.onClick(View.java:3814)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.view.View.performClick(View.java:4424)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Handler.handleCallback(Handler.java:733)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Handler.dispatchMessage(Handler.java:95)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Looper.loop(Looper.java:137)

我在这之后花了几个小时但是找不到问题。谁能帮助我找出我错过的东西?

2 个答案:

答案 0 :(得分:3)

请找到更新的代码并在最后测试,如果您有任何疑问,请告知我们:

package com.example.tabhost;

import java.util.List;
import java.util.Locale;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;

public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
    private Context ContextAsync;
    public MyAsyncTask (Context context){
        this.ContextAsync = context;
    }

    Dialog progress;
    private String providerAsync;
    private LocationManager locationManagerAsync;  
    double   latAsync=0.0;
    double lonAsync=0.0;
    String thikanaAsync="Scan sms for location";

    String AddressAsync="";
    Geocoder GeocoderAsync;

    Location location;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");

    }


    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);


        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        providerAsync = locationManagerAsync.getBestProvider(criteria, false);


        if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            providerAsync = LocationManager.GPS_PROVIDER;
        } else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            providerAsync = LocationManager.NETWORK_PROVIDER;
            /*AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("GPS is disabled in the settings!");
            alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
            alert.setPositiveButton("OK", null);
            alert.show();*/         
        } else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            providerAsync = LocationManager.PASSIVE_PROVIDER;
            //Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
        }    

        location = locationManagerAsync.getLastKnownLocation(providerAsync);
        // Initialize the location fields
        if (location != null) {
            //  System.out.println("Provider " + provider + " has been selected.");
            latAsync = location.getLatitude();
            lonAsync = location.getLongitude();

        } else {
            //Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
        }



        List<Address> addresses = null;
        GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
        try {
            addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);

            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getCountryName();
            AddressAsync = Html.fromHtml(
                    address + ", " + city + ",<br>" + country).toString();
        } catch (Exception e) {
            e.printStackTrace();
            AddressAsync = "Refresh for the address";
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void result) {  

        super.onPostExecute(result);
        progress.dismiss();
        onLocationChanged(location);
        Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
        Intent intentAsync = new Intent(ContextAsync,Emerg.class);
        intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);   
        intentAsync.putExtra("calculated_Lat", latAsync);
        intentAsync.putExtra("calculated_Lon", lonAsync);
        intentAsync.putExtra("calculated_address", AddressAsync);

        ContextAsync.startActivity(intentAsync);

    }



    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
    }

    @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

    }
}

答案 1 :(得分:1)

而不是使用this.ContextAsync = context.getApplicationContext(); ContextAsync应该有Activity个实例,而不是ApplicationContext,所以请this.ContextAsync = context