簡體   English   中英

應用重新啟動后,Android GPS定位不會更新

[英]Android gps loation doesn't update in an app restart

我已經使用Google Maps Api V2在Android中編寫了一個應用程序。 它會定期將gps位置發送到服務器。

問題是它可以在全新安裝中正常運行,並且會定期更新gps坐標,但是當我重新啟動應用程序時,它不會自動更新我的當前位置。

這是我的代碼

    public class MainActivity extends FragmentActivity implements LocationListener {

PendingIntent pendingIntent;
AlarmManager alarmManager;
BroadcastReceiver mReceiver;

// Google Map
GoogleMap googleMap;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//testing from a real server:
private static final String LOC_UPDATE_URL = "http://pissu.com/webservices/addcurrentloc.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

//---lat and long variables
double latitude = 0;
double longitude = 0;


// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 15 * 1; // 15s
// Declaring a Location Manager
protected LocationManager locationManager;

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


    //update current loc
    locationManager = (LocationManager) MainActivity.this
            .getSystemService(LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

    CurrentLocMAP();//to show current loc

    RegisterAlarmBroadcast();

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), 20000 , pendingIntent); //20s
}

private void RegisterAlarmBroadcast() {
    // TODO Auto-generated method stub
    mReceiver = new BroadcastReceiver()
    {
        // private static final String TAG = "Alarm Example Receiver";
        @Override
        public void onReceive(Context context, Intent intent)
        {
            new AttemptSendLoc().execute();
            Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
        }
    };

    registerReceiver(mReceiver, new IntentFilter("sample") );
    pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("sample"),0 );
    alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}

private void UnregisterAlarmBroadcast()
{
    alarmManager.cancel(pendingIntent); 
    getBaseContext().unregisterReceiver(mReceiver);
}


@Override
protected void onDestroy() 
{
    super.onDestroy();
    unregisterReceiver(mReceiver);

}

private void CurrentLocMAP() {
    // TODO Auto-generated method stub
    SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    googleMap = mf.getMap();

    if(googleMap != null){

        googleMap.setMyLocationEnabled(true);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
        String provider=lm.getBestProvider(new Criteria(), true);

        if(provider==null){
            onProviderDisabled(provider);
        }
        Location loc=lm.getLastKnownLocation(provider);


        if (loc!=null){
            onLocationChanged(loc);
        }
    }     
}

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

    LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 16.6));//Animates camera and zooms to preferred state on the user's current location.
    //update();

    latitude = location.getLatitude();
    longitude = location.getLongitude();

    String lati = String.valueOf(latitude);
    String longi = String.valueOf(longitude);

    Toast.makeText(MainActivity.this, lati+ " , " + longi ,Toast.LENGTH_LONG).show();

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

    // 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?");

    // 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);
            MainActivity.this.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();

}

@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

}

public void onBackPressed()
{
    unregisterReceiver(mReceiver);
}



//--------------------------------------------------server send---------------
class AttemptSendLoc extends AsyncTask<String, String, String> {


    boolean failure = false;


    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String lati = String.valueOf(latitude);
        String longi = String.valueOf(longitude);
        String username = "ncbkkk";


        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("longi", longi));
            params.add(new BasicNameValuePair("lati", lati));

            Log.d("request!", "starting");

            //Posting user data to script 
            JSONObject json = jsonParser.makeHttpRequest(
                    LOC_UPDATE_URL, "POST", params);

            // full json response
            Log.d("Post location attempt", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("location Added!", json.toString());    
            }else{
                Log.d("location Failure!", json.getString(TAG_MESSAGE));

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


        return null;

    }
}

}

將“ requestLocationUpdates”以及警報的調度和取消調度移動到onResume()和onPause()而不是onCreate()和onDestroy()。 我認為這將解決您的問題。 我認為正在發生的事情是調用onPause(),此時LocationManager停止發送更新,但是調用了onResume而不是onCreate(),因此您無需重新請求更新。

另外,請考慮登錄onProviderEnabled和onStatusChanged,以便至少知道狀態何時更改。 也許它已被關閉,您根本不知道它,所以您根本不知道。

不相關的評論:不要對用戶將看到的字符串進行硬編碼。 始終使用String資源,以便以后可以輕松地進行國際化。 始終正確執行此操作比稍后審核代碼要容易得多。 AST中的新工具使這一切變得更加容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM