【问题标题】:Getting GPS location and sending it in background获取 GPS 位置并在后台发送
【发布时间】:2016-03-13 13:58:03
【问题描述】:

我编写了一个应用程序,它获取 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
}
}

【问题讨论】:

    标签: android service background gps location


    【解决方案1】:

    您应该创建一个服务而不是活动。有一个使用startForeground() 启动服务的选项,即使您最小化应用程序或使用任务杀手,它也会使服务运行。

    查看question 的例子,例如 startForeground()

    【讨论】:

    • 我试过了,但是 startForeground() 只接受 Notification 作为参数,那么我该如何启动整个函数呢?第二个,我不确定我是否创建了服务正确性。它只是扩展“服务”的java类吗?
    • 请查看答案中问题的链接。您将看到 PlayerService。您的服务类需要扩展 Service 并覆盖方法 onStartCommand、onBind、onDestroy、onCreate... 您可以使用 Intent i=new Intent(this, PlayerService.class); startService(i); 从活动启动服务然后在您的服务中创建通知并调用 startForeground。有关服务生命周期和服务方法的更多信息,请查看here
    • 所以我已经在 onStartCommand 中使用 Thread 和 while(true) 完成了服务。 try catch 中有一个带有 sleep(1000) 的日志。但是在启动线程之后,什么也没有发生。我想在服务中循环整个代码。
    • 先尝试无线程实现Service。只需从 MainActivity 的 onCreate 和 Intent 启动服务,正如我之前写的一条评论并在 onStartCommand 中记录一些内容。在这种情况下,我看不到 try/catch 的意义。
    • 我已经按照你说的做了,而且有效。它显示来自 onStartCommand 方法的吐司,但我想循环一些东西,例如这个吐司。我使用 try /catch 因为在 while 循环中休眠。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    相关资源
    最近更新 更多