Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer in Background

Tags:

I'm developing an Android Application to a college work. In this work I want to create a background service with a timer and when I close the application, timer still running. When I open the app, I can see the time since I've started service. Well, my problem is that when I close the app, the background timer stops and not increments more.

Can you help me please? Thanks a lot

My launcher class

    import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button startButton;
    private Button pauseButton;

    private TextView timerValue;

    Intent intent;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        timerValue = (TextView) findViewById(R.id.timerValue);

        startButton = (Button) findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                intent = new Intent(MainActivity.this, CounterService.class);
                startService(intent);
                registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
            }
        });

        pauseButton = (Button) findViewById(R.id.pauseButton);

        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                unregisterReceiver(broadcastReceiver);
                stopService(intent);
            }
        });

    }

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

            updateUI(intent);       
        }
    };    

    private void updateUI(Intent intent) {
        int time = intent.getIntExtra("time", 0);

        Log.d("Hello", "Time " + time);

        int mins = time / 60;
        int secs = time % 60;
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs));
    }


}

and here, the service class

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;

public class CounterService  extends Service {

    private Intent intent;
    public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";

    private Handler handler = new Handler();
    private long initial_time;
    long timeInMilliseconds = 0L;

    @Override
    public void onCreate() {
        super.onCreate();
        initial_time = SystemClock.uptimeMillis();
        intent = new Intent(BROADCAST_ACTION);  
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();           
            handler.postDelayed(this, 1000); // 1 seconds
        }
    };    

    private void DisplayLoggingInfo() {

        timeInMilliseconds = SystemClock.uptimeMillis() - initial_time; 

        int timer = (int) timeInMilliseconds / 1000;
        intent.putExtra("time", timer);
        sendBroadcast(intent);

    }

    @Override
    public void onDestroy() {   
        super.onDestroy();
        handler.removeCallbacks(sendUpdatesToUI);   

    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


}
like image 698
Luis Avatar asked Nov 02 '13 11:11

Luis


People also ask

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.

How do I keep apps from running in the background on iOS?

For iOS Devices If Background refresh is greyed out in the ON position, go To Settings App - > General - > Background App Refresh - > Turn on the option for the system, and then you can turn on / off by app.


1 Answers

you need to start your service in the onStop() method in your activity like this:

@Override
    protected void onStop() {
        super.onStop();
       //write your code here to start your service
    }
like image 69
Mohsen fallahi Avatar answered Oct 30 '22 23:10

Mohsen fallahi