android应用程序仅在充电时通过互联网发送数据
我正在创建一个Android应用程序,它使用后台服务通过互联网将数据发送到MySql数据库。 该应用程序在插入USB电缆时工作正常,一旦我拔下电缆,它就会继续工作,只是它不会将数据发送到服务器。 负责发送数据的以下类: 1.保存线程:将在检查internet连接后定期发送数据 2.ConnectionStatus检查应用程序是否连接到internet 3.AsyncT负责发送数据android应用程序仅在充电时通过互联网发送数据,android,android-asynctask,Android,Android Asynctask,我正在创建一个Android应用程序,它使用后台服务通过互联网将数据发送到MySql数据库。 该应用程序在插入USB电缆时工作正常,一旦我拔下电缆,它就会继续工作,只是它不会将数据发送到服务器。 负责发送数据的以下类: 1.保存线程:将在检查internet连接后定期发送数据 2.ConnectionStatus检查应用程序是否连接到internet 3.AsyncT负责发送数据 public class SaveThread extends Thread implements Runnable
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;
}
}
public类SaveThread扩展线程实现可运行{
语境;
私人定时器;
专用定时器任务定时器任务;
int当前秒;
国际货币基金组织;
国际时;
公共存储线程(上下文应用程序上下文){
上下文=应用上下文;
startTimer();
}
公共无效startTimer(){
定时器=新定时器();
initializeTimerTask();
timer.schedule(timerTask,0,1000);
}
public void initializeTimerTask(){
timerTask=新的timerTask(){
公开募捐{
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\u DAY);
AppConstant.Hour=当前小时;
AppConstant.Minuts=当前分钟数;
AppConstant.Seconds=当前秒;
如果(currentsecond%AppConstant.FREQ==0){
if(ConnectionStatus.getInstance(context).isconnectedtonework()){
Log.e(AppConstant.Log_标记,“您在线了”^^);
AsyncT AsyncT=new AsyncT();
asyncT.execute();
}否则{
Log.e(AppConstant.Log_标签,“无互联网连接!!!”;
}
}
}
};
}}
公共类连接状态{
私有静态ConnectionStatus实例=新ConnectionStatus();
静态语境;
ConnectivityManager ConnectivityManager;
NetworkInfo wifiInfo、mobileInfo;
布尔连接=假;
公共静态连接Status getInstance(上下文ctx){
context=ctx.getApplicationContext();
返回实例;
}
公共布尔值已连接到网络(){
试一试{
connectivityManager=(connectivityManager)context.getSystemService(context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=connectivityManager.getActiveNetworkInfo();
connected=networkInfo!=null&&networkInfo.isAvailable()&&networkInfo.isConnected();
如果(已连接){
connected=hasActiveInternetConnection();
}
回流连接;
}捕获(例外e){
System.out.println(“检查连接异常:+e.getMessage());
Log.v(AppConstant.Log_标记,例如toString());
}
回流连接;
}
公共静态布尔值hasActiveInternetConnection(){
试一试{
HttpURLConnection urlc=XXXXXXXXXXXXXXXXXX;
setRequestProperty(“用户代理”、“测试”);
setRequestProperty(“连接”、“关闭”);
设置连接超时(1500);
connect();
返回(urlc.getResponseCode()==200);
}捕获(IOE异常){
Log.e(AppConstant.Log_标记,“错误检查互联网连接”,e);
}
返回false;
}
}
公共类AsyncT扩展了AsyncTask{
字符串ServerURL=XXXXXXXX;
字符串响应服务器;
@凌驾
受保护的空位背景(空位…空位){
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(服务器URL);
试一试{
JSONObject jsonobj=新的JSONObject();
jsonobj.put(“H”,AppConstant.Hour);
jsonobj.put(“M”,AppConstant.Minuts);
jsonobj.put(“S”,AppConstant.Seconds);
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“req”,jsonobj.toString());
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
InputStream InputStream=response.getEntity().getContent();
InputStreamToString示例str=新的InputStreamToString示例();
responseServer=str.getStringFromInputStream(inputStream);
Log.e(AppConstant.Log_标记,“response-----------------------------”+AppConstant.Collecting_日期);
Log.e(AppConstant.Log_标记,“response---------------------------------------+responseServer);
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
}
根据您对定期发送数据的描述,WorkManager可能是一个更好的解决方案,尤其是因为您自己做了很多API已经为您做的事情。有很多关于如何使用它的资源,包括。我怀疑这是因为打瞌睡模式:@SergeyGloov谢谢你的回答,但你知道如何防止这种情况发生。@SergeyGloov谢谢,你是对的,你救了我很多,谢谢。你能写一个答案并描述一下你是如何为未来的访问者解决这个问题的吗?