Reputation: 81
I'm creating an app for Android in Java. I can send info to a webservice but when i'm offline i want to store the info and when the phone gets connected to the internet i want to send it to the webservice. Can anyone help me? Thanks
Upvotes: 1
Views: 8001
Reputation: 41
Store your data in SQLite data-base. You can read here.
Check in BroadcastReceiver if connectivity changed and update online DB and delete the content from Sqlite DB.
public void onReceive(Context context, Intent intent) {
String s = intent.getAction();
if (s.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
if (IsNetworkAvailable(context)) {
// update your online data-base and delete all rows from SQlite
}
return;
}
}
Method isNetworkAvailable:
public static boolean isNetworkAvailable(Context mContext) {
Context context = mContext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
You also need permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Upvotes: 3
Reputation: 1953
Offline storage and sync seem simple at first sight but you need to be careful and consider the following:
First get familiar with the storage options available in the platform and chose the most convenient for your app scenario.
Second, design your sync mechanism in an efficient way so your app won't drain the battery life.
This is a good resource to check the entire structure of an android app that cares about working offline and properly sync with the server as network becomes available.
Upvotes: 2
Reputation: 1208
In the event, where you upload your data, check if Internet connection is available or not, if not, store the data as textfile or object and name it like needToUpload1, 2, 3.
Then, whenever the device is online, check if the there is any file named like that. If so, upload it via service and delete the file.
That's just my opinion how i'll do it but really depends on data. You can find how to do every step on this site so i hope it will help.
Upvotes: 1
Reputation: 2202
Save your info to a SQLite
database and use a BroadcastReceiver
to listen when network connection is available. When connection is available, start a Service
that sends the saved data to your webservice.
Upvotes: 1