简体   繁体   中英

android app send data over the internet only when charging

I am creating an Android application that sends data to MySql database over the internet using background service. the application works perfectly when it is plugged to USB cable, once I remove the cable it keeps working except that it does not send the data to the server. the following classes that are responsible for sending the data: 1. Save thread: will send the data periodically after checking the internet connection 2. ConnectionStatus checks if the app is connected to the internet or not 3. AsyncT responsible on sending the data

public class SaveThread extends Thread implements Runnable{
    Context context;
    private Timer timer;
    private TimerTask timerTask;
    int currentsecond;
    int currentminut;
    int currenthour;

    public SaveThread (Context applicationContext) {
        context=applicationContext;
        startTimer();
    }

    public void startTimer() {
        timer = new Timer();
        initializeTimerTask();
        timer.schedule(timerTask, 0, 1000);
    }

    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                Calendar rightNow = Calendar.getInstance();
                Date currentTime = Calendar.getInstance().getTime();
                currentsecond = rightNow.get(Calendar.SECOND);
                currentminut = rightNow.get(Calendar.MINUTE);
                currenthour = rightNow.get(Calendar.HOUR_OF_DAY);

                AppConstant.Hour = currenthour;
                AppConstant.Minuts = currentminut;
                AppConstant.Seconds =currentsecond;


                if (currentsecond%AppConstant.FREQ == 0) {
                    if (ConnectionStatus.getInstance(context).isConnectedTONetwork()) {
                        Log.e(AppConstant.LOG_TAG, "You are online ^_^ ");
                        AsyncT asyncT = new AsyncT();
                        asyncT.execute();

                    } else {
                        Log.e(AppConstant.LOG_TAG, "No internet connection !!!");
                    }
                }
            }
        };
    }}


public class ConnectionStatus {
    private static ConnectionStatus instance = new ConnectionStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static ConnectionStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isConnectedTONetwork() {
        try {
            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
            if (connected){
                connected = hasActiveInternetConnection();
            }
            return connected;
        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v(AppConstant.LOG_TAG, e.toString());
        }
        return connected;
    }

    public static boolean hasActiveInternetConnection() {
        try {
            HttpURLConnection urlc = XXXXXXXXXXXXXXXXX;
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(AppConstant.LOG_TAG, "Error checking internet connection", e);
        }
        return false;
    }
}



public class AsyncT extends AsyncTask<Void, Void, Void> {
    String ServerURL = XXXXXXXX;
    String responseServer;

    @Override
    protected Void doInBackground(Void... voids) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(ServerURL);

        try {
            JSONObject jsonobj = new JSONObject();

            jsonobj.put("H", AppConstant.Hour);
            jsonobj.put("M", AppConstant.Minuts);
            jsonobj.put("S", AppConstant.Seconds);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            InputStream inputStream = response.getEntity().getContent();
            InputStreamToStringExample str = new InputStreamToStringExample();
            responseServer = str.getStringFromInputStream(inputStream);
            Log.e(AppConstant.LOG_TAG, "response ------------------" + AppConstant.Collecting_date);
            Log.e(AppConstant.LOG_TAG, "response ------------------" + responseServer);

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

        return null;
    }
}

Based on your description that you are sending data periodically, WorkManager might be a better solution for you, especially since you are doing a lot yourself that the API already does for you. There are a lot of resources on how to use it, including samples, code-labs and blogs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM