获取GPS位置并在后台发送

时间:2016-03-13 13:58:03

标签: android service background gps location

我写了一个获取GPS位置的应用程序,并通过HTTP帖子将其发送到我的服务器。现在我想做,按下主页按钮并将其最小化后,应用程序仍将从GPS发送数据。我发现了IntentServices的内容,但我不知道如何使用它。 这是我的代码:

public class MainActivity extends AppCompatActivity implements LocationListener{


public CharSequence message;
public String log;

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

    //int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

}

@Override
public void onLocationChanged(Location location){
    double latitude = (location.getLatitude());
    double longitude = (location.getLongitude());

    message = "Latitude: " + latitude + ", Longitude: " + longitude;
    Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
    Calendar calendar = Calendar.getInstance();
    String year = Integer.toString(calendar.get(Calendar.YEAR));
    String month = Integer.toString(calendar.get(Calendar.MONTH));
    String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
    String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
    String min = Integer.toString(calendar.get(Calendar.MINUTE));
    log = year+"/"+month+'/'+day+" "+hour+":"+min+" w:"+latitude+" h:"+longitude;
    Log.v("log: ", log);

    //whole asynctask is about sending data only

    new AsyncTask<Void, Void, Void>(){
        @Override
        protected void onPreExecute(){
            Log.v("AsyncTask: ", "starting");
        }

        @Override
        protected Void doInBackground(Void ...params){

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://server/php.php");

            try{
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("log", log));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                try {
                    HttpResponse response = httpClient.execute(httpPost);
                } catch (IOException e){
                    Log.v("error: ", "IOException");
                }


            } catch (UnsupportedEncodingException e){
                e.printStackTrace();
                Log.v("error: ", "UnsupportedEncodingException");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void res){
            Log.v("AsyncTask: ", "Ended");
        }
    }.execute();

}

@Override
public void onProviderDisabled(String provider){
    // TODO Auto-generator 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 个答案:

答案 0 :(得分:0)

您应该创建服务而不是活动。可以选择使用startForeground()启动服务,即使最小化应用程序或使用任务杀手,服务也会运行。

请查看question,例如startForeground()

的用法