我的项目必须在服务器和移动设备之间发送和接收大量数据。
如果互联网信号较弱,可能会发生数据丢失。
在计划中使用sqlite。并定期与服务器数据库同步。
有没有人可以解释我如何使用sqlite有效地与服务器db同步并通知sqlite本地数据已在服务器db中更新?
针对此问题的任何其他建议。
提前致谢。
答案 0 :(得分:3)
首先检查 Internet连接是否存在,如果是,则进行服务器通信,如果否,则将数据保存在 Sqlite 本地数据库中。
如果成功进行服务器通信,则会定期检查互联网连接是否已将数据库值发送到服务器。
ConnectionDetector类:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)
_context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
<强> MainActivity:强>
public class LeadLogin extends Activity {
ConnectionDetector cd;
Boolean isInternetPresent = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
editor = sharedPreferences.edit();
cd = new ConnectionDetector(LeadLogin.this);
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent){
// if internet connection present
// communicate with server
}else{
// internet connection not present
// add values into database
}
}
}
StartService类:
public class StartService extends Service {
Timer timer = new Timer();
private final int TIME_INTERVAL = 100000;
ConnectionDetector cd;
Boolean isInternetPresent = false;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(isInternetPresent)
{
doTimerThings();
}
return super.onStartCommand(intent, flags, startId);
}
private void doTimerThings()
{
timer.scheduleAtFixedRate(new TimerTask() {
@SuppressLint("DefaultLocale")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void run() {
// check database value if here, if they are present then send to the server and delete from the database
}
}, 0, TIME_INTERVAL);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
答案 1 :(得分:1)
完成本教程..
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
记住 - &GT;当您向服务器发送数据时,服务器将以200
确定
(如果成功)状态
码。这告诉您数据已成功发送到服务器。因此,您可以执行的操作是删除sqllite
中的数据(当且仅当收到200
时)。