Check for new chat messages at background, Android - android

I'm developing a application when which every 4,5 seconds the client checks whether the server responds "OK".
It's even working, But if I turn on/off the internet sometimes it stops working, it is inconsistent and I need to check the messages accurately.
And service stop like in example I gave and it re-operate outside the specified range of seconds (4.5)
I'm developing a chat, and I need to know this precisely, I need to be professional.
Start.java
public class Start extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Intent serviceIntent = new Intent(getBaseContext(), BackExec.class);
getBaseContext().startService(serviceIntent);
}
#Override
protected void onResume()
{
super.onResume();
Intent serviceIntent = new Intent(getApplicationContext(), BackExec.class);
startService(serviceIntent);
}}
BackExec.java
public class BackExec extends Service {
static Timer t;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
}
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
return START_STICKY;
}
public static String getData(){
URL site = null;
try {
site = new URL("http://192.168.0.10:8080/example/server.php");
URLConnection urlConn = site.openConnection();
urlConn.setRequestProperty("Cookie", CookieManager.getInstance().getCookie("http://192.168.0.10:8080/example"));
urlConn.setDoOutput(true);
PrintStream enviarInfos = new PrintStream(urlConn.getOutputStream());
enviarInfos.print("pac=pac");
urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
String out = "";
while ((inputLine = in.readLine()) != null)
out = out + inputLine;
in.close();
return out;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public void onStart(Intent intent, int startId) { } // TO DO
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {} }

Related

Converting my Background Service to Android Oreo 8.0 Compatible

I have a service in my App which handles number of things. Sometimes when device is idle, the app crashes. And I know about the new Android 8.0 guidelines but I am not sure If I should convert my service to JobScheduler or take any other correct way. I can use some suggestions on which will be the best way to convert this service. Here is the code
HERE IS THE SERVICE :
public class ConnectionHolderService extends Service {
private static final String LOG_TAG = ConnectionHolderService.class.getSimpleName();
private SensorManager mSensorManager;
private static ConnectionHolderService instance = null;
public static ConnectionHolderService getInstanceIfRunningOrNull() {
return instance;
}
private class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
//some code
}
}
private Messenger mMessenger = new Messenger(new IncomingHandler());
public ConnectionHolderService() {
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
//some code
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private void startListeningForShake() {
mShakeEnabled = true;
startServiceToAvoidStoppingWhenNoClientBound(ACTION_STOP_SHAKE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
}
private void startServiceToAvoidStoppingWhenNoClientBound(String action) {
registerReceiver(mReceiver, new IntentFilter(action));
startService(new Intent(this, ConnectionHolderService.class));
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ":Doze lock");
if (!lock.isHeld()) {
lock.acquire();
}
// When the Shake is active, we should not stop when UI unbinds from this service
startNotification();
}
private Notification getShakeServiceForegroundNotification() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (mShakeEnabled) {
notificationBuilder.addAction(0, getString(R.string.shake_turn_off),
PendingIntent.getBroadcast(this,
REQ_CODE_STAY_ON,
new Intent(ACTION_STOP_SHAKE),
PendingIntent.FLAG_UPDATE_CURRENT));
}
if (mPollingEnabled) {
// notificationBuilder.addAction(0, getString(R.string.stop_smart_home_integration),
// PendingIntent.getBroadcast(this,
// REQ_CODE_STAY_ON,
// new Intent(ACTION_STOP_POLLING_SQS),
// PendingIntent.FLAG_UPDATE_CURRENT));
}
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
notificationBuilder
.setSmallIcon(R.drawable.logo)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setUsesChronometer(true)
.setContentIntent(PendingIntent.getActivity(this, REQ_CODE_STAY_ON, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle(getString(R.string.title_notification_running_background))
.setContentText(getString(R.string.description_running_background));
return notificationBuilder.build();
}
private void stopIfNeeded() {
if (!mShakeEnabled && !mPollingEnabled) {
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
// It can be IllegalStateException
}
stopNotification();
stopSelf();
if (lock != null && lock.isHeld()) {
lock.release();
}
}
}
public void startNotification() {
if (SqsPollManager.sharedInstance().isConnectInBackground() && !MyApp.sharedInstance().isAppInForeground()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
startForeground(ID_SHAKE_SERVICE, getShakeServiceForegroundNotification());
}
}
}
public void stopNotification() {
mNotificationManager.cancel(ID_SHAKE_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
stopForeground(true);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mReceiver = null;
Log.i(LOG_TAG, "onDestroy");
mMessenger = null;
mSensorListener = null;
instance = null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "onTaskRemoved! Stopping ConnectionHolderService");
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
}
stopNotification();
stopSelf();
if (lock != null && lock.isHeld()) {
lock.release();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
stopForeground(true);
}
stopSelf();
}
}
HERE IS MY APP CLASS:
public class MyApp {
#Override
public void onCreate() {
super.onCreate();
sendMessageToConnectionHolderService("SomeMessage");
}
public void sendMessageToConnectionHolderService(final int what) {
bindService(new Intent(this, ConnectionHolderService.class), new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(LOG_TAG, "ConnectionHolderService connected!");
Messenger messenger = new Messenger(service);
Message msg = new Message();
msg.what = what;
try {
messenger.send(msg);
Log.i(LOG_TAG, "Message " + what + " has been sent to the service!");
} catch (RemoteException e) {
Log.e(LOG_TAG, "Error sending message " + msg.what + " to ConnectionHolderService", e);
}
final ServiceConnection conn = this;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
unbindService(conn);
}
}, 1000);
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(LOG_TAG, "ConnectionHolderService disconnected!");
}
}, Context.BIND_AUTO_CREATE);
}
private Runnable mStartNotificationRunnable = new Runnable() {
#Override
public void run() {
if (SqsPollManager.sharedInstance().isPollingEnabled()
&& SqsPollManager.sharedInstance().isConnectInBackground()
&& !isAppInForeground()) {
if (null != ConnectionHolderService.getInstanceIfRunningOrNull()) {
ConnectionHolderService.getInstanceIfRunningOrNull().startNotification();
}
}
}
};
private Runnable mStopNotificationRunnable = new Runnable() {
#Override
public void run() {
if (null != ConnectionHolderService.getInstanceIfRunningOrNull()) {
ConnectionHolderService.getInstanceIfRunningOrNull().stopNotification();
}
}
};
}
AndroidManifest :
<service
android:name=".ConnectionHolderService"
android:enabled="true"
android:exported="false" />
You should consider using WorkManager. There are a lot of resources on how to use it, including samples, code-labs and blogs.
And if you are interested in JobScheduler in particular because of the Android 8.0 guidelines, I wrote a blog post that provides insights.

Android keep download onging even after clearing app from recent task

I am using service to download a file , but if I clear the app from recent app list then download stopped . I tried running the service as foreground but no luck . How can I achieve it ? Download multiple files in queue , even after remove the app from recent task .
public class ApkDownloadService extends Service {
public static final String EXTRA_APP_DETAILS = ApkDownloadService.class.getName().concat("_app_details");
int NOTIFICATION_ID = ((Number) System.currentTimeMillis()).intValue();
private String TAG = "ApkDownloadService";
String appId;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
NotificationManagerCompat notificationManager;
NotificationCompat.Builder mBuilder;
// Issue the initial notification with zero progress
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
int fileLength;
#Override
public void onCreate() {
super.onCreate();
notificationManager = NotificationManagerCompat.from(this);
Log.d(TAG,"onCreate");
}
#Override
public void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
Log.d(TAG,"onDestroy");
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
notificationManager.cancel(NOTIFICATION_ID);
Log.d(TAG,"onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG,"onBind");
return null;
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG,"onUnbind");
return super.onUnbind(intent);
}
#SuppressLint("StaticFieldLeak")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
assert intent != null;
Result result = intent.getParcelableExtra(EXTRA_APP_DETAILS);
Log.d(TAG,"onStartCommand");
appId = result.getApplicationId();
mBuilder = new NotificationCompat.Builder(this, appId);
mBuilder.setContentTitle(result.getName())
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW);
mBuilder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
startForeground((int) result.getId(), mBuilder.build());
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
URL url;
try {
url = new URL(result.getPackage().getApk());
URLConnection conection = url.openConnection();
conection.connect();
fileLength = conection.getContentLength();
long total = 0;
int count, tmpPercentage = 0;
InputStream input = url.openStream();
byte[] chunk = new byte[4096];
while ((count = input.read(chunk)) != -1) {
total += count;
outputStream.write(chunk, 0, count);
PROGRESS_CURRENT = (int) ((total * 100) / fileLength);
if (PROGRESS_CURRENT > tmpPercentage) {
EventBus.getDefault().post(String.valueOf(PROGRESS_CURRENT)); // Posting download percentage
mBuilder.setContentText(PROGRESS_CURRENT + "%");
mBuilder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
tmpPercentage = PROGRESS_CURRENT;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onCancelled() {
super.onCancelled();
Log.d(TAG,"onCancelled");
}
}.execute();
return START_REDELIVER_INTENT;
}
}
I am not sure what is wrong with my foreground service . If I clear the app from recent task , download stops .

Schedule Asynctask - While? Service? Timer?

Ok, I got a Togglebutton that starts a service. The service starts a new Thread in onStartCommand. In this Thread an Asynctask is executed.
Now I want this Asynctask to be executed for example every 5 seconds. The Asynctask checks if the website is available.
-> if no, after 5 secs check again
-> if yes, show message and stop
Whats the best method with my already present code:
public class NotifiyService extends Service {
String savedsa;
Thread Th1;
boolean value;
final class TheThread implements Runnable{
int serviceID;
String savedsa1;
TheThread(int serviceID,String savedsa){
this.serviceID = serviceID;
this.savedsa1 = savedsa;
}
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value,savedsa1);
new HttpTask().execute(httpparams);
}
}
public NotifiyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences7 = getSharedPreferences("Prefsa",MODE_WORLD_READABLE);
savedsa = sharedPreferences7.getString("keysa","");
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted)+ "\n" + savedsa,Toast.LENGTH_LONG).show();
Th1 = new Thread(new TheThread(startId,savedsa));
Th1.start();
return START_STICKY;
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
private static class HttpTaskParams{
boolean value;
String address;
HttpTaskParams(boolean value, String address){
this.value = value;
this.address = address;
}
}
private class HttpTask extends AsyncTask<HttpTaskParams,Void,Boolean>{
#Override
protected Boolean doInBackground(HttpTaskParams... params) {
boolean value = params[0].value;
String address = params[0].address;
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLights(Color.YELLOW,600,600);
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
#Override
public void run() {
ScheduledExecutorService checkreg = Executors.newScheduledThreadPool(1);
scheduledFuture = checkreg.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value, savedsa1);
new HttpTask().execute(httpparams);
}
}, 0, 20, TimeUnit.SECONDS);}
#Override
public void onDestroy() {
//super.onDestroy();
Th1.interrupt();
scheduledFuture.cancel(false);
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
stopSelf();
}
I think a ScheduledExecutorService could help you.
Please check this answer.
Please let me know if this helps you.
try this /**
* Loads exchange rates form network periodically
* Returns results in broadcast message.
* Created by koss on 19.02.16.
* */
public class EcbEuropeService extends Service {
public static final String ECB_URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
public static final int UPDATE_PERIOD = 30000;
public static final int UPDATE_TICK = 1000;
public static final String NOTIFICATION = "koss.ru.oneclickrate.receiver";
public static final String EXTRA_CURRENCIES_MAP = "extra_currencies_map";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getUrlData();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public Cubes getUrlData() {
(new AsyncTask<Object, Object, Cubes>() {
Map<CurrencyType, BigDecimal> result = new EnumMap<CurrencyType, BigDecimal>(CurrencyType.class);
#Override
protected Cubes doInBackground(Object... params) {
Cubes cubes = new Cubes();
InputStream is = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(ECB_URL);
urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
cubes = EcbEuropeResponseParser.parse(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection!=null) IOUtils.close(urlConnection);
if(is!=null) IOUtils.closeQuietly(is);
return cubes;
}
}
#Override
protected void onPostExecute(Cubes map) {
super.onPostExecute(map);
sendBroadcastMessage(map);
startTimer();
}
}).execute();
return null;
}
/**
* Restarts timer
* */
public void startTimer() {
cdt.cancel();
cdt.start();
}
CountDownTimer cdt = new CountDownTimer(UPDATE_PERIOD, UPDATE_TICK) {
#Override
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
getUrlData();
}
};
private void sendBroadcastMessage(Cubes currenciesMap) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(EXTRA_CURRENCIES_MAP, currenciesMap);
sendBroadcast(intent);
}
}

Update android Textview continuously

I am working on an Android Application which have an one activity class and service class. In service, Continuous bulk data (1090 bytes) will be received every 10 milliseconds. I need to update the text view continuously with these bulk data. What is recommended way to update Text view from a continuous background service?
Service Class
public class RecepService extends Service {
public static Handler mHandler;
StringBuilder hexstring;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
init();
}
private void init() {
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
byte[] readBuf = (byte[]) msg.obj;
int readBuflen = msg.arg1;
// here will receive 1090 bytes of data
// every 10 milliseconds
Receivepatientattributes(readBuf,readBuflen);
}
}
};
}
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
MainActivity.recep.setText(MainActivity.recep.getText().toString() + "\t" +
"" + total_data );
}
String bytetohex(byte[] txt, int len) {
String p="";
byte[] text = new byte[len];
text = txt;
hexstring = new StringBuilder();
for (int j = 0; j < len; j++) {
String hex= Integer.toHexString(0xFF & txt[j]);
if (hex.length()==1) {
hexstring.append("0");
}
hexstring.append(hex+" ");
}
p=p+hexstring.toString();
return p;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
If you want to use Schedule and timer task then you can See My Answer
To solve current issue follow this bellow instructions.
Suppose your activity has a Broadcast Receiver
private BroadcastReceiver mReceiver;
Then you override methods onResume() where your broadcast receiver will be registered and also onPause() where will your receiver be unregistered:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter(
"android.intent.action.MAIN");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract your message from intent
String msg_for_me = intent.getStringExtra("YOUR_MESSAGE");
//log your message value
Log.i("MyTag", msg_for_me);
}
};
//registering your receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregister your receiver
this.unregisterReceiver(this.mReceiver);
}
Here the broadcast receiver is filtered via android.intent.action.MAIN and from Service the message will BroadCast using this filter
Now your Method Receivepatientattributes will like this :
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
Intent i = new Intent("android.intent.action.MAIN").putExtra("YOUR_MESSAGE", total_data);
this.sendBroadcast(i);
}
Thats it. :)
User LocalBroadcastManager
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
Intent intent = new Intent("update-text");
// add data
intent.putExtra("message", total_data);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
In MainActivity
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("update-text"));
}
private boolean mCanBeUpdated = true;
private static final int ONE_SEC = 1000; //ms
private static final int RECEPTION_SPEED = 10; //ms
private static final int CYCLES = (int) (ONE_SEC / RECEPTION_SPEED);
private int mCurrentCycle = -1;
private String mMsgCache = "";
// handler for received Intents for the "update-text" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
mMsgCache = mMsgCache + "\t" + message;
if (mCanBeUpdated) {
// No problem updating UI here, refer --> http://stackoverflow.com/a/5676888/1008278
final Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
MainActivity.recep.append(mMsgCache);
mMsgCache = "";
}
});
mCanBeUpdated = false;
} else if (mCurrentCycle >= CYCLES) {
mCurrentCycle = -1;
mCanBeUpdated = true;
} else {
mCurrentCycle++;
}
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
Reference
You can use Timer for Continously updating your textview.
Set value in preferences every time when your service is running with the latest value.
Now in Timer get that value from preferences and update your TextView with that value.
Here is some code :
class UpdateTimeTask extends TimerTask {
public void run() {
textview.setText("updated value");
}
}
Set in onCreate ();
Timer timer = new Timer();
UpdateTimeTask UpdateTimeTask = new UpdateTimeTask ();
timer.schedule(UpdateTimeTask, 1000);
Use handler beacuse A Handler allows communicating back with UI thread from other background thread.
boolean handlerStop = false;
void handleHandler(){
Handler handler =new Handler();
final Runnable r = new Runnable() {
public void run() {
handler.postDelayed(this, 30000);
if(!handlerStop) {
updateTextView() //update your text with other thread like asyncronous thread
}
}
};
handler.postDelayed(r, 0000);
}
#Override
public void onResume() {
super.onResume();
handlerStop=false;
handleHandler();
}
#Override
public void onPause() {
super.onPause();
handlerStop=true;
handleHandler();
}
#Override
public void onStop() {
super.onStop();
handlerStop=true;
handleHandler();
}

Why does this service stop?

I have the following Service that is meant to check a web API.
The Implementation is meant to retry the HTTP request 5 times before issuing a notification.
Anyway it seems that the service simply stops after the first attempt.
Please what is going on???
public class CreditcheckService extends IntentService {
public CreditcheckService() {
super("CreditcheckService");
}
#Override
protected void onHandleIntent(Intent intent) {
String phone = "";
phone = intent.getStringExtra("phone");
checkcreditonline(phone);
Log.e("inizio il service","inizio il service");
}
private void checkcreditonline(final String phone) {
final Handler h = new Handler();
final JsonHttpResponseHandler jsonHttpResponseHandler = new JsonHttpResponseHandler() {
private int counter = 0;
#Override
public void onSuccess(JSONObject arg0) {
int cazzo=0;
cazzo++;
try {
String status = arg0.getString("credit");
} catch (JSONException e) {
e.printStackTrace();
}
try {
String status = arg0.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
//IF FAILED SHOULD RETRY, BUT IT DOESN'T
if (counter < 5) {
//HERE THE SUCCESSIVE ATTEMPTS
h.postDelayed(new WebserviceRunnable(this, phone), 5000);
} else {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(CreditcheckService.this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getResources().getString(R.string.unable_to))
.setContentText(getResources().getString(R.string.please_connect));
mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0));
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(999, mBuilder.build());
}
counter++;
}
};
h.post(new WebserviceRunnable(jsonHttpResponseHandler, phone));
}
private class WebserviceRunnable implements Runnable {
private JsonHttpResponseHandler jsonHttpResponseHandler;
private String email;
public WebserviceRunnable(
JsonHttpResponseHandler jsonHttpResponseHandler, String aEmail) {
this.jsonHttpResponseHandler = jsonHttpResponseHandler;
this.email = aEmail;
}
public void run() {
try {
WebServiceApi.get(
"rest/credit/get/" + URLEncoder.encode(email, "utf-8"),
null, jsonHttpResponseHandler);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
onHandleIntent in IntentService is asynchronous.
When onHandleIntent exits, the Service is stopped.
So don't post a message to a Handler, instead do it directly in checkcreditonline().

Categories

Resources