获取 GPS 位置并在后台发送

Getting GPS location and sending it in background

我编写了一个获取 GPS 位置并通过 HTTP post 将其发送到我的服务器的应用程序。现在我想做的是,按下主页按钮并将其最小化后,应用程序仍会从 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
}
}

您应该创建服务而不是 Activity。有一个选项可以使用 startForeground() 启动服务,这使得服务 运行 即使您最小化应用程序或使用任务杀手。

查看 question startForeground()

用法的示例