2017-07-11 3 views
0

Ich habe ein Projekt Sonnenschein erstellt, die wetterbedingtes Detail durch Tracking Ihrer aktuellen Standort gibt es funktioniert gut, aber manchmal meine GPSTracker-Klasse, die mir die Breite, Länge und Postleitzahl zusammen mit dem Land gibt nicht die Daten an der Zeit und dann zeigt meine App dann den NetzwerkfehlerGPS Standorte Android

Ich weiß nicht, was das Problem manchmal funktioniert es sehr gut, aber manchmal tut es nicht.

Meine GPSTracker Klasse: -

package com.example.na462.sunshine; 

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

import android.Manifest; 
import android.app.AlertDialog; 
import android.app.Service; 
import android.content.ContentValues; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.util.Log; 


public class GPSTracker extends Service implements LocationListener { 
private final Context mContext; 

//flag for GPS Status 
boolean isGPSEnabled = false; 

//flag for network status 
boolean isNetworkEnabled = false; 

boolean canGetLocation = false; 

Location location; 
public double latitude; 
public double longitude; 

//The minimum distance to change updates in metters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters 

//The minimum time beetwen updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

//Declaring a Location Manager 
protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

     //getting GPS status 
     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     GPSEnabled.GPS = isGPSEnabled; 

     //getting network status 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 

      int afl = ContextCompat.checkSelfPermission(mContext, 
        Manifest.permission.ACCESS_FINE_LOCATION); 

      int acl = ContextCompat.checkSelfPermission(mContext, 
        Manifest.permission.ACCESS_COARSE_LOCATION); 

    if (locationManager != null) { 

     Log.d("locationManager",""+locationManager); 

       if (afl != PackageManager.PERMISSION_GRANTED && acl != PackageManager.PERMISSION_GRANTED) { 
        // TODO: Consider calling 
        // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
        // here to request the missing permissions, and then overriding 
        // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
        //           int[] grantResults) 
        // to handle the case where the user grants the permission. See the documentation 
        // for Activity#requestPermissions for more details. 
        return location; 
       } 
       location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
       updateGPSCoordinates(); 
      } 

      //if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

        Log.d("GPS Enabled", "GPS Enabled"); 

        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         updateGPSCoordinates(); 
        } 
       } 
      } 
     } 
    } catch (Exception e) { 
     //e.printStackTrace(); 
     Log.e("Error : Location", "Impossible to connect to LocationManager", e); 
    } 

    return location; 
} 

public void updateGPSCoordinates() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
    } 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
*/ 

public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

/** 
* Function to get latitude 
*/ 
public double getLatitude() 
{ 
    if (location != null) 
    { 
     latitude = location.getLatitude(); 
    } 

    return latitude; 
} 

/** 
* Function to get longitude 
*/ 
public double getLongitude() 
{ 
    if (location != null) 
    { 
     longitude = location.getLongitude(); 
    } 

    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
*/ 
public boolean canGetLocation() 
{ 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
*/ 
public void showSettingsAlert() 
{ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    //Setting Dialog Title 
    alertDialog.setTitle("Alert Title"); 

    //Setting Dialog Message 
    alertDialog.setMessage("gpsmessage"); 

    //On Pressing Setting button 
    alertDialog.setPositiveButton(0, new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    //On pressing cancel button 
    alertDialog.setNegativeButton("cancle", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      dialog.cancel(); 
     } 
    }); 

    alertDialog.show(); 
} 

/** 
* Get list of address by latitude and longitude 
* 
* @return null or List<Address> 
*/ 

public List<Address> getGeocoderAddress(Context context) { 


    if (location != null) { 

     Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
     try { 
      List<Address> addresses = geocoder.getFromLocation(latitude, 
        longitude, 1); 
      return addresses; 
     } catch (IOException e) { 
      // e.printStackTrace(); 
      Log.e("Error : Geocoder", "Impossible to connect to Geocoder", 
        e); 
     } 
    } 

    return null; 
} 

/** 
* Try to get AddressLine 
* 
* @return null or addressLine 
*/ 
public String getAddressLine(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 
     String addressLine = address.getAddressLine(0); 

     return addressLine; 
    } else { 
     return null; 
    } 
} 

/** 
* Try to get Locality 
* 
* @return null or locality 
*/ 
public String getLocality(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 
     String locality = address.getLocality(); 

     return locality; 
    } else { 
     return null; 
    } 
} 

/** 
* Try to get Postal Code 
* 
* @return null or postalCode 
*/ 
public String getPostalCode(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 
     String postalCode = address.getPostalCode(); 

     return postalCode; 
    } else { 
     return null; 
    } 
} 

/** 
* Try to get CountryName 
* 
* @return null or postalCode 
*/ 
public String getCountryName(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 
     String countryName = address.getCountryName(); 

     return countryName; 
    } else { 
     return null; 
    } 
} 

public void onProviderDisabled(String provider) { 
} 

public void onProviderEnabled(String provider) { 
} 

public void onStatusChanged(String provider, int status, Bundle extras) { 
} 

public void onLocationChanged(Location location) { 
    // TODO Auto-generated method stub 

} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 
} 

Und meine Splash Aktivität, wo ich für Postleitzahl und andere Sachen bin anspruchsvoll: Hinweis ValuetoPass, Koordinaten und CordinateLoc sind andere Klassen in anderem activitites für das Bestehen der Informationen, die ich habe sie verwendet

package com.example.na462.sunshine; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Handler; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.animation.Animation; 
import android.view.animation.AnimationUtils; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.net.URL; 

import static android.R.attr.animation; 
import static com.example.na462.sunshine.R.id.MainList; 

public class SplashActivity extends Activity implements Animation.AnimationListener { 
Animation animation,TextAnimation; 
Double Latitude; 
Double Longitude; 
String Country; 
ImageView imageView; 
ImageView ErrorImage; 
TextView AnimationText; 
Button ErrorReload; 
LinearLayout Layout; 
String PostalCode; 
Receiver receiver; 
boolean Connection; 
GPSTracker gpsTracker; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_splash); 
    AnimationText = (TextView)findViewById(R.id.TextAnimation); 
    ErrorReload = (Button)findViewById(R.id.ErrorReload); 
    imageView = (ImageView)(SplashActivity.this).findViewById(R.id.Animation); 
    Layout = (LinearLayout)findViewById(R.id.Error); 
    ErrorImage = (ImageView)findViewById(R.id.Nointernet); 
    gpsTracker = new GPSTracker(SplashActivity.this); 
    gpsTracker.getLocation(); 
    receiver = new Receiver(); 
    Connection = receiver.internetconnection(SplashActivity.this); 

    if(!Connection || !GPSEnabled.GPS){ 
     imageView.setVisibility(View.INVISIBLE); 
     Layout.setVisibility(View.VISIBLE); 
     ErrorImage.setVisibility(View.VISIBLE); 
     AnimationText.setVisibility(View.INVISIBLE); 

    } 
    else { 
     AnimationText.setVisibility(View.VISIBLE); 
     imageView.setVisibility(View.VISIBLE); 
     Layout.setVisibility(View.INVISIBLE); 
     ErrorImage.setVisibility(View.INVISIBLE); 

     new Handler().postDelayed(new Runnable() { 
      public void run() { 
       Intent i = new Intent(SplashActivity.this, ScrollingActivity.class); 
       startActivity(i); 
       overridePendingTransition(R.anim.fade_in, R.anim.fade_out); 
       finish(); 
      } 
     }, 8000); 



     animation = AnimationUtils.loadAnimation(this, R.anim.fade_in); 
     animation.setAnimationListener(this); 
     imageView.startAnimation(animation); 


     TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink); 
     TextAnimation.setAnimationListener(this); 
     AnimationText.startAnimation(TextAnimation); 

     new FetchGPS().execute(); 

    } 
} 

private class FetchGPS extends AsyncTask<Void,Void,String>{ 

    @Override 
    protected String doInBackground(Void... voids) { 
     Latitude = gpsTracker.getLatitude(); 
     Longitude = gpsTracker.getLongitude(); 
     Country = gpsTracker.getCountryName(SplashActivity.this); 
     PostalCode = gpsTracker.getPostalCode(SplashActivity.this); 
     CordinatesLoc.Latitude = Latitude; 
     CordinatesLoc.Longitude = Longitude; 
     CordinatesLoc.CLatitude = Latitude; 
     CordinatesLoc.CLongitude = Longitude; 
     CordinatesLoc.Country = Country; 
     Coordinates.Latitude = String.valueOf(Latitude); 
     Coordinates.Longitude = String.valueOf(Longitude); 
     CordinatesLoc.Postal = PostalCode; 
     ValuesToPass.Pincode = PostalCode; 
     ValuesToPass.Country = "in"; 
     return PostalCode; 

    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
    } 
} 

@Override 
public void onAnimationStart(Animation animation) { 

} 

@Override 
public void onAnimationEnd(Animation animation) { 

} 

@Override 
public void onAnimationRepeat(Animation animation) { 

} 

// Its an onclick Method For Retry if there isnt any conncection or GPS Estabished 


public boolean ErrorReload(View V){ 
    imageView.setVisibility(View.INVISIBLE); 
    Layout.setVisibility(View.INVISIBLE); 
    AnimationText.setVisibility(View.INVISIBLE); 
    ErrorImage.setVisibility(View.INVISIBLE); 
    gpsTracker.getLocation(); 
    Connection = receiver.internetconnection(SplashActivity.this); 
    if(!Connection || !GPSEnabled.GPS){ 
     imageView.setVisibility(View.INVISIBLE); 
     Layout.setVisibility(View.VISIBLE); 
     ErrorImage.setVisibility(View.VISIBLE); 
     return false; 
    } 
    AnimationText.setVisibility(View.VISIBLE); 
    imageView.setVisibility(View.VISIBLE); 
    Layout.setVisibility(View.INVISIBLE); 
    ErrorImage.setVisibility(View.INVISIBLE); 

    new Handler().postDelayed(new Runnable() { 
     public void run() { 
      Intent i = new Intent(SplashActivity.this, ScrollingActivity.class); 
      startActivity(i); 
      overridePendingTransition(R.anim.fade_in, R.anim.fade_out); 
      finish(); 
     } 
    }, 8000); 


    animation = AnimationUtils.loadAnimation(this, R.anim.fade_in); 
    animation.setAnimationListener(this); 
    imageView.startAnimation(animation); 




    TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink); 
    TextAnimation.setAnimationListener(this); 
    AnimationText.startAnimation(TextAnimation); 


    new FetchGPS().execute(); 
    return true; 
} 

}

+0

Es gibt viele Themen über GPSTracker, einfach versuchen zu finden. Sie können auch dieses Blog lesen http://gabeschansoftware.com/location-tracking – Blackkara

+0

https://stackoverflow.com/questions/43082062/code-will-only-return-0-0-0-0-gps-coordinate- while-werting-nullpointerexceptio – CommonsWare

Antwort

0

ich denke, Sie sollten Ihre manifest.mf Datei überprüfen. Vielleicht müssen Sie eine Erlaubnis hinzufügen, um Ihr Smartphone zu finden.

0

ich denke Code funktioniert gut ... manchmal kann GPS Koordinaten in Gebäuden nicht verfolgen. Die beste Lösung ist die Verwendung von fusionierten Location-Provider api