I want to update the UI every 5 seconds after calling a web service even if the app is closed. I have created a service and using broadcast receiver i am getting the data from server but when the application is closed the last response from server should be updated, but when i open the app last response data is not updated.
Below is the code snippet
MainActivity.java
import java.text.DateFormat;
import org.json.JSONArray;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView name1, name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView)findViewById(R.id.name);
name1 = (TextView)findViewById(R.id.name1);
startService(new Intent(MainActivity.this, YourService.class));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String nameStr = intent.getStringExtra("name");
String name1Str = intent.getStringExtra("name1");
name.setText(nameStr);
name1.setText(name1Str);
}
};
@Override
protected void onResume()
{
super.onResume();
//registerReceiver(statusReceiver,mIntent);
LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(
mMessageReceiver, new IntentFilter("UIValues"));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="12dp"
android:hint="md5"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
<TextView
android:id="@+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="12dp"
android:hint="name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
</LinearLayout>
YourService.java
import learn2crack.asynctask.library.JSONParser;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
new JSONParse().execute();
/// Any thing you want to do put the code here like web service procees it will run in ever 1 second
handler.postDelayed(this, 5000); // 5 seconds
}
};
@Override
public void onStart(Intent intent, int startid) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000);//1 second
Log.d(TAG, "onStart");
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url); // server url
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject reader = new JSONObject(json.toString());
String name = reader.getString("name");
String name1 = reader.getString("name1");
Intent intent = new Intent("UIValues");
intent.putExtra("name", name);
intent.putExtra("name1", name1);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.asynctask.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.asynctask.YourService"></service>
</application>
</manifest>
Can anyone help me solving this issue. Thanks in advance
You should probably save the last response in persistant storage (file, sharedprefernce) and simply read it once the app is opened and show the last response.