If you think the Android project android-training-tutorial listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package im.ene.dev.zbroadcastreceiver.services;
//fromwww.java2s.comimport android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
publicclass CustomBroadcastService extends Service {
publicstaticfinal String BROADCAST_ACTION = "im.ene.broadcast_action";
private Intent mIntent;
privateint counter;
private Handler mHandler;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
publicvoid onCreate() {
/* this intent will be used to send broadcast */
mIntent = new Intent(CustomBroadcastService.BROADCAST_ACTION);
counter = 0;
mHandler = new Handler();
super.onCreate();
}
@Override
publicint onStartCommand(Intent intent, int flags, int startId) {
mHandler.postDelayed(mSendBroadcastRunnable, 500);
return super.onStartCommand(intent, flags, startId);
}
public Runnable mSendBroadcastRunnable = new Runnable() {
@Override
publicvoid run() {
sendBroadcastToUpdateUI();
mHandler.postDelayed(this, 1000);
}
};
publicvoid sendBroadcastToUpdateUI() {
counter++;
mIntent.putExtra("text", counter + "");
sendBroadcast(mIntent);
}
@Override
publicvoid onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}