0
Me developing a test application in which a Service
is running in Background and is sending notifications to your phone every 10 seconds. To improve the test I created a counter that increases with each notification sent. The Service
works almost perfectly, however, if I open and close the APP the counter restarts to 1 and I have no idea why.
I talked about closing the APP and not minimizing, there is a big difference between minimize the APP and close, if I minimize remains normal but if I close it yes the counter restarts.
Service class:
public class BackgroundService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
public sattic int j = 1;
@Override
public void onCreate() {
new Thread() {
@Override
public void run() {
while (true) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(BackgroundService.this)
.setContentTitle("Notificação: " + j)
.setContentText("Texto da notificação: " + j)
.setTicker("Texto que aparece ao receber a notificação.")
.setBadgeIconType(R.drawable.error)
.setSmallIcon(R.drawable.help)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
j++;
try {
Thread.sleep(10000);
} catch (Throwable e) {
Log.create(e);
}
}
}
}.start();
}
}
Main class:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getBaseContext(), BackgroundService.class));
}
}
In short, if I open the app the counter and the notifications work normally, however if I close the application the counter restarts from 1 (the notifications keep appearing but the counter restarts). I talked about closing the APP and not minimizing, there is a big difference between minimize the APP and close, if I minimize remains normal but if I close it yes the counter restarts.
I already tried to put the counter variable inside the Thread
but it didn’t work it restarts the same way.
I don’t get it. It’s not natural to reboot?
– Reginaldo Rigo
@So you’re telling me that it’s normal to reboot? If I had it there instead of an int a Socket would I lose the connection? Or if I had saved a user name too for example, I would lose it just because it closed the App?
– Eduardo Mior