Search code examples
androidservicebroadcastreceiver

How to stop updating the UI (via Service)?


I've got an application which, after the user enters a number of seconds and presses a button, the screen turns off and a timer starts (with the number of seconds inputted). The screen turns on and the service stops, only after the timer ends.

Now, when the timer ends, I also want a TextView to change. Currently, I have set a variable (counterr; see it in MainService) to keep increasing after five seconds (see the "sendUpdatesToUI" function, from MainService), but I want said variable to only increase once and only AFTER the service stops.

Any ideas how?

MainActivity:

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText timer = (EditText) findViewById(R.id.insertTimer);

        findViewById(R.id.startApp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainService.class);
                intent.putExtra("timer", timer.getText().toString());
                registerReceiver(broadcastReceiver, new IntentFilter(MainService.BROADCAST_ACTION));

                Toast.makeText(MainActivity.this, "Countdown, Started", Toast.LENGTH_SHORT).show();
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000);

                startService(intent);
            }
        });
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateUI(intent);
        }
    };

    private void updateUI(Intent intent) {
        String counter = intent.getStringExtra("counter");
        TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
        txtCounter.setText(counter);
    }
}

MainService:

    public class MainService extends Service {

    public static final String BROADCAST_ACTION = "package com.example.vladpintea.friendsbeforecents.displayevent";
    private final Handler handler = new Handler();
    Intent intent;
    int counterr = 0;

    String usedTimer;
    long interval;

    //TimerTask that will cause the run() runnable to happen.
    TimerTask myTask = new TimerTask() {
        public void run() {
            stopSelf();
        }
    };
    //Timer that will make the runnable run.
    Timer myTimer = new Timer();

    private boolean isRunning  = false;

    @Override
    public void onCreate() {
        intent = new Intent(BROADCAST_ACTION);

        registerReceiver(counter, new IntentFilter(Intent.ACTION_SCREEN_ON));

        Toast.makeText(MainService.this, "Service, Created", Toast.LENGTH_SHORT).show();

        isRunning = true;
    }

    private BroadcastReceiver counter = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainService.this, "Whoops! You've Lost.", Toast.LENGTH_SHORT).show();
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        usedTimer = intent.getStringExtra("timer");
        try {
            interval = Long.parseLong(usedTimer);
        } catch (NumberFormatException nfe) {

        }

        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

        Toast.makeText(MainService.this, "Service, Started", Toast.LENGTH_SHORT).show();

        myTimer.schedule(myTask, interval);
        return super.onStartCommand(intent, flags, startId);
    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();
            handler.postDelayed(this, 5000);
        }
    };

    private void DisplayLoggingInfo() {
        intent.putExtra("counter", String.valueOf(++counterr));
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
        wakeLock.acquire();

        Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);

        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Solution

  • Call DisplayLoggingInfo() only in onDestroy() if you want to increase the counter only once.