0
点赞
收藏
分享

微信扫一扫

Android 在Service服务中上传数据到服务器

前言:根据自己的项目去总结的一个思路,和具体实现方法。

思路:在项目中创建一个服务类UserlogService 继承自Service
之后根据Service的生命周期。
Service的生命周期这一块,可以看我的这篇博文,​​Service的详解​​,就不在本篇文章中讲解了。
根据Service生命周期,把具体操作写在onStartCommand()中。
onStartCommand()的代码如下:
定期触发3秒上传一次

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHelper = UserLogDBHelper.getInstance(this, 1);
mHelper.openReadLink();
myhandler.sendMessageDelayed(Message.obtain(myhandler, 1), 3000);
return START_STICKY;
}

1.查询本地没有上传的数据。

//查询本地未上传数据
ArrayList<UserLog> arrayListlog = readSQLite();

调用readSQLite方法:

//查询本地数据
private ArrayList<UserLog> readSQLite() {
ArrayList<UserLog> arrayList = mHelper.query("1=1");
return arrayList;
}

2.调用API,上传数据,这一步才是核心。
这里面用的是Post异步请求

/**调用API,上传数据
* @param userLog
*/
private void setUploaddata(final UserLog userLog) {
try {
String userlogjson = new Gson().toJson(userLog);
//定义OKhttp
OkHttpClient okHttpClient = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json");
//定义请求体
RequestBody body = RequestBody.create(JSON, userlogjson);

Request request = new Request.Builder()
.post(body)
.url("http://v.juhe.cn/toutiao/index")
.build(); //异步请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}
@Override
public void onResponse(Call call, Response response) throws IOException {
String ss = response.body().string();
ResultMsg resultMsg = new Gson().fromJson(ss, ResultMsg.class);
if (resultMsg.Result.equals("1")) {
Log.d(TAG, "run: 上传成功");
Looper.prepare();
//上传成功的数据从本地删除
Delete(userLog.UserLogID);
Looper.loop();
} else {

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

}

3.上传数据之后,从本地删除已经上传的数据,上面代码已经写出
这是Delete()的具体方法。

//删除本地数据
private void Delete(String UserLogID)
{
try {
mHelper.delete("UserLogID='" + UserLogID+"'");
}catch (Exception ex)
{
Log.d(TAG, "Delete: "+ex.toString());
}

}

最后一步,在MainActivity中,启动服务。

//开启日志上传服务
Intent intent=new Intent(this,UserLogService.class);
startService(intent);

以上就是上传到服务器的一个基本思路,仅做记录参考,有需要的可以参考学习!


举报

相关推荐

0 条评论