java - 应用隐藏时如何发送和接收数据?

标签 java android json android-asynctask httpurlconnection

当应用程序隐藏或屏幕关闭时,我的应用程序不会将 JSON 字符串发送到 PHP 脚本。我使用 HttpURLConnection。我的应用程序发送 GPS 位置。我希望该应用程序能够像信使一样在后台运行。发送和接收数据发生在 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;
    }

}

像这样吗?

最佳答案

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

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

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

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

关于java - 应用隐藏时如何发送和接收数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33484330/

相关文章:

android - 使用 HMS Toolkit 将 GMS 转换为 HMS

javascript - 如何在jsp中创建一个json对象?

php - 完整日历 - 向事件对象添加额外属性

jquery - 无法在jquery中解析json

java - 动态设置 OpenCSVReader 映射的类类型和类

java - 如何在openCV中将轮廓转换到图像的中心?

android - 如何从 rss URL 读取 RSS 提要?

java - 如何解析带有分隔符的文本?

java - 我如何在 gradle 中打印出 JAVA 类路径?

android - 我正在使用 Toast 在 ListViewItem 单击时显示,但没有显示 toast