You can receive updates for your activity from service, please see this counter example to get help in doing it.
CounterUpdates.java
package yourPackage;
public class CounterUpdates {
private static CounterUpdates mInstance;
private ICounterUpdates mListener;
private CounterUpdates() {}
public static CounterUpdates getInstance() {
if(mInstance == null) {
mInstance = new CounterUpdates();
}
return mInstance;
}
public void setListener(ICounterUpdates listener) {
mListener = listener;
}
public void onCountUpdate(int count) {
if(mListener != null) {
mListener.onCountUpdate(count);
}
}
// Definition of location updates interface
public interface ICounterUpdates {
public void onCountUpdate(int count);
}
}
CounterService.java
package yourPackage;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class CounterService extends Service {
private Handler mHandler = new Handler();
private int mCount = 0;
private static final int INTERVAL = 500;
private Runnable mRunnableCounter = new Runnable() {
@Override
public void run() {
deliverResults(++mCount);
mHandler.postDelayed(this, INTERVAL);
}
};
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
startCounterThread();
return START_STICKY;
}
private void startCounterThread() {
mCount = 0;
mHandler.postDelayed(mRunnableCounter, INTERVAL);
}
private void stopCounterThread() {
mHandler.removeCallbacks(mRunnableCounter);
}
public static void deliverResults(int count) {
CounterUpdates.getInstance().onCountUpdate(count);
}
@Override
public void onDestroy() {
super.onDestroy();
stopCounterThread();
}
@Override
public IBinder onBind(final Intent intent) {
return null;
}
}
AndroidManifest.xml (Register your service)
<service android:name="yourPackage.CounterService" />
To Start Service Use this code:
startService(new Intent(this, CounterService.class));
YourActivity.java
public class YourActivity extends Activity implements CounterUpdates.ICounterUpdates {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
CounterUpdates.getInstance().setListener(this);
}
@Override
public void onCountUpdate(int count) {
((TextView) findViewById(R.id.textView)).setText("Count: " + count);
}
}
I hope it will work, best of luck :)