我正在创建一个Android应用程序,该应用程序使用后台服务通过互联网将数据发送到MySql数据库。当应用程序插入USB电缆时,它可以完美地工作,一旦我拔下电缆,它就可以继续工作,除非它不将数据发送到服务器。负责发送数据的以下类:1.保存线程:检查网络连接后会定期发送数据2.ConnectionStatus检查应用程序是否连接到互联网3.AsyncT负责发送数据
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;
}
}
根据您对定期发送数据的描述,WorkManager可能是您更好的解决方案,尤其是因为您自己做了很多API已经为您做的事情。关于如何使用它,有很多资源,包括示例、代码实验室和博客。