1
I created a simple android app that starts a service soon when I click a button I put, just click the button it starts the service immediately.
What I want now is that clicking the service button takes some time to start. how can I do this??
Here’s the code that launches the service:
public class NotifyService extends Service {
private HandlerThread handlerThread;
private Handler handler;
private boolean started = false;
//Define o tempo entre notificações, altere como quiser
private final int TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS = 7;
@Override
public void onCreate() {
Log.d("NotifyService", "onCreate");
handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("NotifyService","onStart");
if(!started) {
Log.d("NotifyService","Notificações iniciadas");
started = true;
Runnable runnable = new Runnable() {
@Override
public void run() {
sendNotification();
handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
}
};
handler.post(runnable);
}
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("NotifyService","Notificações terminadas");
handlerThread.quit();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void sendNotification(){
Intent intent = new Intent (this ,
Bca.class);
PendingIntent pendingIntent = PendingIntent.getActivity
(this, 0, intent, 0);
Notification notification = new Notification.Builder (this)
.setContentTitle("Qsmobile")
.setContentText("Consulte a sua fila")
.setSmallIcon(R.drawable.bcno)
.setContentIntent(pendingIntent)
.getNotification();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager =
(NotificationManager) getSystemService (NOTIFICATION_SERVICE);
notificationManager.notify (0, notification);
Log.d("NotifyService", "notificação enviada");
}
}
It is not very logical to create a new Thread and then execute the code in the original Thread (the one where Handler was created).
– ramaral