Android gps位置在应用重启时不会更新

时间:2014-08-17 18:36:27

标签: android gps location locationmanager

我使用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;

    }
}

}

1 个答案:

答案 0 :(得分:0)

移动&#34; requestLocationUpdates&#34;以及将警报调度和取消调度到onResume()和onPause()而不是onCreate()和onDestroy()。我认为这将解决您的问题。我认为正在调用的是onPause(),此时LocationManager停止发送更新,但调用onResume而不是onCreate(),因此您不会重新请求更新。

另外,请考虑登录onProviderEnabled和onStatusChanged,以便至少知道状态何时发生变化。也许它被关闭了,你不知道它,因为你根本没有记录它。

不相关的评论:不要硬编码用户会看到的字符串。始终使用String资源,以便以后轻松实现国际化。比以后审计代码更容易做到这一点。 AST中的新工具使这更容易。