Вопрос

hi people, I try to read as many of the GPS data here. Resp. I would like to identify the location. I now have pretty much all the suggestions but nothing runs through it here. getLastKnownLocation () always returns null. And the app crashes. Can someone help me here one? Here is my code.

MyManifest

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.xxx.xxxbrokenstream"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="de.xxx.xxxbrokenstream.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

MainActivity

package de.xxx.xxxbrokenstream;

import de.xxx.xxxbrokenstream.R;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContextWrapper;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public abstract class MainActivity extends Activity implements LocationListener {

ContextWrapper context;
double longitude;
double latitude;

private LocationManager locationManager;
private boolean isGps, isNetwork;
private double currentLat, currentLong;
private Location location;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setDefaultButton();

    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);

    isGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    isNetwork = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            1000, 0, this);

    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 1000, 0,
            this);

    getCurrentLocation();



};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
};

public void setDefaultButton() {
    Button buttonstream1 = (Button) findViewById(R.id.btn_stream1);
    buttonstream1 .setVisibility(View.VISIBLE);
    buttonstream1 .setOnClickListener(stream1Listener);

    Button buttonstream2 = (Button) findViewById(R.id.btn_stream2);
    buttonstream2 .setVisibility(View.VISIBLE);
    buttonstream2 .setOnClickListener(stream2Listener);

    Button buttonstream3 = (Button) findViewById(R.id.btn_stream3);
    buttonstream3 .setVisibility(View.VISIBLE);
    buttonstream3 .setOnClickListener(stream3Listener);

 };

// Listener

 LocationListener locationListener = new LocationListener() {

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

     public void onProviderEnabled(String provider) {
     }

     public void onProviderDisabled(String provider) {
     }

     public void onLocationChanged(Location location) {
         try {
             if (location != null) {
                currentLat = location.getLatitude();
                currentLong = location.getLongitude();
             }
        } catch (Exception e) {
            e.printStackTrace();
         }
     }

};

private OnClickListener stream1Listener = new OnClickListener() {
    public void onClick(View v) {
        // do something when the button is clicked

    }

};

private OnClickListener stream2Listener = new OnClickListener() {
    public void onClick(View v) {

    }
};

private OnClickListener stream3Listener = new OnClickListener() {
    public void onClick(View v) {

    }
};

private void destroyAll() {
    if (locationManager != null)
        locationManager.removeUpdates(this);
}

@Override
public void onDestroy() {
   super.onDestroy();
   destroyAll();
}

/**
 * Get the current location..
 */
public void getCurrentLocation() {
    if (isNetwork) {
        location = locationManager
                   .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    } else if (isGps) {
        location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    }
    if (location != null) {
        currentLong = location.getLongitude();
        currentLat = location.getLatitude();

    } else {
        currentLong = 0.0;
        currentLat = 0.0;
    }
}

public double getCurrentLat() {
    return currentLat;
}

public void setCurrentLat(double currentLat) {
    this.currentLat = currentLat;
}

public double getCurrentLong() {
    return currentLong;
}

public void setCurrentLong(double currentLong) {
    this.currentLong = currentLong;
}

 }

Edit:

hi, thanks. I have changed my code. Unfortunately I get the same result. The app is crashed. this is the log from eclipse log:

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{de.xxx.xxxbrokenstream/de.xxx.xxxbrokenstream.MainActivity}: java.lang.InstantiationException: can't instantiate class de.xxx.xxxbrokenstream.MainActivity at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.InstantiationException: can't instantiate class de.xxx.xxxbrokenstream.MainActivity at java.lang.Class.newInstanceImpl(Native Method) at java.lang.Class.newInstance(Class.java:1319) at android.app.Instrumentation.newActivity(Instrumentation.java:1054) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)

Это было полезно?

Решение

Try this way : Your utility class

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; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 40; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 10000 * 60 * 1; // 10 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);
        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // 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);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}
@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }
    return longitude;
}
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("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.ic_launcher_web);

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", 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("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }      
}
}

Call from your activity

public void getLocation() {
    GPSTracker gps = new GPSTracker(this);
    if(gps.canGetLocation()){ 
        double lat = gps.getLatitude(); // returns latitude
        double lng = gps.getLongitude(); // returns longitude
        Global_reco.latitudeTmp = String.valueOf(lat);
        Global_reco.longitudeTmp = String.valueOf(lng);
    }
    if(!gps.canGetLocation())
    {
        gps.showSettingsAlert();
    }
}

It works for all devices... Hope this help

This code come from http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top