【问题标题】:How to send and receive a data when app is hidden?隐藏应用程序时如何发送和接收数据?
【发布时间】:2015-11-02 18:22:08
【问题描述】:

当应用程序被隐藏或屏幕关闭时,我的应用程序不会向 PHP 脚本发送 JSON 字符串。我使用 HttpURLConnection。我的应用程序发送 GPS 位置。我希望该应用程序可以像 messanger 一样在后台工作。发送和接收数据发生在 AsyncTask 中。怎么了?

public class MyAsyncTask extends AsyncTask<JSONObject, Void, JSONObject> {

    String addr = GlobalConfig.addr;
    String prot = GlobalConfig.prot;
    int port = GlobalConfig.port;

    @Override
    protected void onPreExecute() {

    }

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

        JSONObject json = params[0];
        String string = "json="+json;

        try {

            URL url = new URL(prot,addr,port,"json/myLocation.php");

            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setDoInput(true);
            httpCon.setUseCaches(false);
            httpCon.setConnectTimeout(15000);
            httpCon.setRequestProperty("Content-Length", Integer.toString(string.length()));
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestMethod("POST");

            DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
            wr.writeBytes(string);
            wr.flush();
            wr.close();

            int responseCode = httpCon.getResponseCode();

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

        return null;

    }

    @Override
    protected void onPostExecute(JSONObject json) {

    }

}


public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    boolean isGPSEnabled = false;

    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

    private static final long MIN_TIME_BW_UPDATES = 10000;

    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {

            } else {
                this.canGetLocation = true;

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

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }


    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }


    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        return latitude;
    }


    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        return longitude;
    }


    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        alertDialog.setTitle("GPS is settings");

        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

        int ID = GlobalConfig.ID;
        int Random = GlobalConfig.Random;

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

        try {

            JSONObject json = new JSONObject();
            json.put("ID", ID);
            json.put("Random", Random);
            json.put("latitude", latitude);
            json.put("longitude", longitude);

            new MyAsyncTask().execute(json);

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

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

像这样?

【问题讨论】:

  • 请发布您的代码并进一步清除您的问题

标签: java android json android-asynctask httpurlconnection


【解决方案1】:

我认为你在混合不同的东西:

AsyncTask 意味着代码在单独的任务(线程)中运行,但仍在您的活动上下文中。这意味着它在您的应用程序的后台运行,并且不会停止您的应用程序的执行。

服务能够在没有任何活动上下文的情况下在后台执行代码。这就像在系统的背景中一样。

要实现您想要的,您必须将您的任务放在服务中。

【讨论】:

    【解决方案2】:

    正如克里斯蒂安所说,如果您想在应用程序处于后台时更新坐标,您将需要一个服务。

    该服务将实现位置监听器,当位置更新时,您将运行异步任务。

    【讨论】:

    • 我更新了我的帖子。我的代码包含您正在编写的服务,但它不发送数据。 GPSTracker 是一项服务。当位置改变时,JSONObject 被传输到 AsyncTask。
    • @SeaDog 是的,这就是你需要做的,但不要忘记清单文件以便它运行
    • 我添加了条目: 够了吗?
    • 太棒了! :) Please accept the answer
    【解决方案3】:

    您需要多种因素才能完成这项工作。

    首先,您需要了解如何让您的服务具有粘性。为此,请按照此处的步骤操作:

    Android Service needs to run always (Never pause or stop)

    粘性服务是在您明确告诉它关闭之前一直运行的服务 (http://developer.android.com/reference/android/app/Service.html#START_STICKY)

    您还想根据文档查看wakefulBroadcastReceiverhttps://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

    这样当设备在关机后重新启动或启动时,它会再次启动您的服务。

    为了更加安全,您还需要查看实现某种形式的network broadcast receiver,例如通过在此处实现解决方案:Broadcast receiver for checking internet connection in android app

    最后一个是为了让您在没有网络连接时不要尝试发送内容,而是在设备重新联机时启动服务。

    不过,我建议您谨慎行事。您一直在运行、一直在上传的服务会消耗大量电量,也许您想限制它发送的数据量和它收集这些数据的时间间隔,但这取决于您是否收听 :)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-06
      • 2012-12-09
      • 2013-07-04
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      相关资源
      最近更新 更多