Countdown timer not run when user close application - android

I had created countdown timer to display timeout it works well when user minimize application but it stops when user close application. i had added code below kindly help me it's an emergency.
this is MainActivity.java
public static final String TAG = "Demo";
TextView t1 ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.t1);
startService(new Intent(this, count_servie.class));
}
private BroadcastReceiver br = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
}
};
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(count_servie.COUNTDOWN_BR));
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
t1.setText("Countdown seconds remaining: " + millisUntilFinished / 1000);
}
}
this is my count_servie.java
public class count_servie extends Service {
public static final String COUNTDOWN_BR = "com.demo.DSemo.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
public void onCreate() {
super.onCreate();
cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
public void onFinish() {
}
};
cdt.start();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent arg0) {
return null;
}
Thanks in advance.

You need to return START_STCKY in your onStartCommand() method for the service to run even when app is closed.
....
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STCKY;
}
....
You can refer thislink for correctly implementing a service.
Alternatively, you can refer this SO question.
Update
Use a Foreground Service to avoid your Service being killed. In order to make your service Foreground, replace your onStartCommand code with this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Timer")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
public void onFinish() {
stopForeground(true);
}
};
cdt.start();
return START_STICKY;
}
Udpate 2: Counter using Service and SharedPreferences
Replace your Actvity's code with this:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v4.os.ResultReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String SHARED_PREF = "MyPref";
private final static int MAX_COUNTER = 30;
public static final String KEY_COUNTER_SECONDS = "seconds";
public static final String KEY_SAVED_COUNTER = "saved_counter";
public static final String KEY_SAVED_TIME_MILLI = "saved_time_milli";
MyResultReceiver mReceiver;
TextView mTvCounter;
SharedPreferences mSharedPref;
long mMaxCounterValueInSeconds = MAX_COUNTER;
long mCurCounterValue = 0;
boolean mShouldSaveValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvCounter = (TextView) findViewById(R.id.tv_counter);
mReceiver = new MyResultReceiver(null);
mSharedPref = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
//register listener
MyService.registerReceiver(mReceiver);
//get values from shared pref
long savedCounter = mSharedPref.getLong(KEY_SAVED_COUNTER, -1);
long savedTime = mSharedPref.getLong(KEY_SAVED_TIME_MILLI, -1);
//if -1 counter was running when app was closed, get saved values from shared pref
if (savedTime != -1) {
//elapsedTime is the time spent in seconds while the app was in background
long elapsedTime = (getCurrentTimeInMilli() - savedTime)/1000; //convert to sec
mCurCounterValue = savedCounter + elapsedTime;
if(mCurCounterValue < MAX_COUNTER){
//calculate current counter value from values retrieved from shared pref
mMaxCounterValueInSeconds = MAX_COUNTER - mCurCounterValue;
//start the value with updated max count value
startService(mMaxCounterValueInSeconds);
}else{
mCurCounterValue = MAX_COUNTER;
}
}else{
//if counter was not running, start the service with max count value = MAX_COUNTER
startService(mMaxCounterValueInSeconds);
}
//update text view
mTvCounter.setText("" + mCurCounterValue);
}
private void startService(long maxCounter){
mShouldSaveValues = true;
Intent intent = new Intent(this, MyService.class);
Bundle bundle = new Bundle();
bundle.putLong(KEY_COUNTER_SECONDS, maxCounter);
intent.putExtras(bundle);
startService(intent);
}
#Override
protected void onPause() {
super.onPause();
//stop the service
stopService(new Intent(this, MyService.class));
//unregister listener
MyService.unregisterReceiver();
if(mShouldSaveValues) {//save the values only when counter has started
//save values in the shared preference
SharedPreferences.Editor editor = mSharedPref.edit();
Log.d(TAG, "saving counter: " + Long.parseLong(mTvCounter.getText().toString()));
editor.putLong(KEY_SAVED_COUNTER, Long.parseLong(mTvCounter.getText().toString()));
editor.putLong(KEY_SAVED_TIME_MILLI, getCurrentTimeInMilli());
editor.apply();
}
}
/**
* This method returns current time in milli seconds
*
* #return time in milliseconds
*/
private long getCurrentTimeInMilli() {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long timeInMilli = date.getTime();
return timeInMilli;
}
/**
* ResultReceiver is used to get values from MyService.class
* It is registered in onResume() &
* unregistered in onPause()
*/
class MyResultReceiver extends ResultReceiver {
public MyResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
String strMilliFinished = resultData.getString(MyService.KEY_MSG);
updateUI(Long.parseLong(strMilliFinished));
}
private void updateUI(final long milliFinished) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mCurCounterValue++;
mTvCounter.setText("" + mCurCounterValue);
if(milliFinished == 0) {
//resetting counter values
mShouldSaveValues = false;
mMaxCounterValueInSeconds = MAX_COUNTER;
mCurCounterValue = 0;
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putLong(KEY_SAVED_COUNTER, -1);
editor.putLong(KEY_SAVED_TIME_MILLI, -1);
editor.apply();
}
}
});
}
}
}
Replace your Service code with this:
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.os.ResultReceiver;
import android.util.Log;
public class MyService extends Service {
public static final String KEY_MSG = "msg";
CountDownTimer cdt = null;
private static ResultReceiver mReceiver;
public MyService() {
}
public static void registerReceiver(ResultReceiver receiver) {
mReceiver = receiver;
}
public static void unregisterReceiver() {
mReceiver = null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
long maxCounterValueInSeconds = bundle.getLong(MainActivity.KEY_COUNTER_SECONDS);
long maxCounter = maxCounterValueInSeconds * 1000;
cdt = new CountDownTimer(maxCounter, 1000) {
public void onTick(long millisUntilFinished) {
sendMessage(1, "" + millisUntilFinished);
}
public void onFinish() {
sendMessage(1, "" + 0);
stopSelf();
}
};
cdt.start();
return START_STICKY;
}
private void sendMessage(int resultCode, String message) {
if (mReceiver != null) {
Bundle bundle = new Bundle();
bundle.putString(KEY_MSG, message);
mReceiver.send(resultCode, bundle);
}
}
#Override
public void onDestroy() {
super.onDestroy();
cdt.cancel();
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
Note: I am using ResultReceiver instead of BroadcastReciver

Related

how to pass a string data to my activity from a service

I have an activity that runs a timer and I want to broadcast that timer and set a receiver to my activity and display the timer. I know that it can be done using a broadcast and receiving that broadcast intent but I don't know how to do it.
here are my codes
public class MyService extends Service {
private Vibrator v;
NotificationCompat.Builder notification;
private static final int uniqueID = 71399;
#Override
public void onCreate() {
super.onCreate();
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences = getSharedPreferences("Timer", Context.MODE_PRIVATE);
int dur = sharedPreferences.getInt("duration", 0);
//background timer
CountDownTimer countDownTimer = new CountDownTimer(dur, 1000) {
#Override
public void onTick(long dur) {
long millis= dur;
String hms= String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
//seconds
,TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
startnotif(hms);
startBroadcast(hms);
}
#Override
public void onFinish() {
long n[] = {1,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000};
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(n, -1);
endnotif();
onDestroy();
}
};
countDownTimer.start();
return START_STICKY;
}
public void onDestroy() {
stopSelf();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//notification
public void startnotif(String hms)
{
String noT = hms;
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setTicker("apps are blocked!");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Be productive!");
notification.setContentText(hms);
ClickNotif();
}
public void endnotif(){
notification.setContentText("00:00");
notification.setTicker("apps are now unblocked!");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("You survived!");
notification.setContentText("Apps are now unblocked!");
ClickNotif();
}
//other parts of notif
public void ClickNotif(){
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
The Target activity
public class Main2Activity extends AppCompatActivity {
private Button btntest;
private TextView timer;
private Spinner spinner, spinner2;
public int hours, mins, duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btntest = (Button) findViewById(R.id.startbtn);
timer = (TextView) findViewById(R.id.Timertxt);
//setting up 2 spinners
spinner = (Spinner) findViewById(R.id.hrspinner);
String [] values = {"00","01","02","03","04","05","06"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
spinner2 = (Spinner) findViewById(R.id.minspinner);
String [] values2 = {"00","01","10","20","30","40","50","60"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, values2);
adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter2);
//button start
btntest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spin=spinner.getSelectedItem().toString();
hours = Integer.parseInt(spin);
hours = hours*3600000;
String spin2=spinner2.getSelectedItem().toString();
mins = Integer.parseInt(spin2);
mins = mins*60000;
duration = hours+mins;
setParam(duration);
startService(duration);
}
});
}
/*timer part
public void setParam(int param){
CountDownTimer countDownTimer = new CountDownTimer(param, 1000) {
#Override
public void onTick(long param) {
long millis= param;
String hms= String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
//seconds
,TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
timer.setText(hms);
}
#Override
public void onFinish() {
timer.setText("00:00");
}
};
countDownTimer.start();
}*/
//saving data and passing intent to service
public void startService(int duration)
{
int d = duration;
SharedPreferences sharedPreferences = getSharedPreferences("Timer", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("duration", d);
editor.apply();
Intent intent = new Intent(this,MyService.class);
startService(intent);
}
}
how can I show that timer to my text field? Please help!
you can use LocalBroadcastManager like this :
in your service
private LocalBroadcastManager broadcaster;
#Override
public void onCreate() {
broadcaster = LocalBroadcastManager.getInstance(this);
}
private void sendData(){
Intent intent = new Intent("MyData");
broadcaster.sendBroadcast(intent);
}
and call sendData() wherever you want, and in your activity write
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
/*
this called when app receive notification and MainActivity is opened
* see FcmMessagingService.class to see where it called
*/
#Override
public void onReceive(Context context, Intent intent) {
// Log.d("broadcaster", "onReceive BaseActivity");
// write whatever you want and you cant use intent.getString("key");
}
};
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver), new IntentFilter("MyData"));
}

Running countdown timer faster when i back to activity

I make a service for countdown timer, in activity i put a text view for show time every seconds: 100 - 0, but when i leave activity and back to that. i see timer as run very fast, but i want to this run just every second. where is problem ?
MainActivity:
public static final String mBroadcastIntegerAction = "com.example.broadcast.integer";
private IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showTime = (TextView) findViewById(R.id.textView1);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(mBroadcastIntegerAction);
Intent serviceIntent = new Intent(this, AppServiceDay.class);
startService(serviceIntent);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(mBroadcastIntegerAction)) {
int second = intent.getIntExtra("Time", 0);
showTime.setText("" + second);
}
}
};
#Override
protected void onPause() {
registerReceiver(mReceiver, mIntentFilter);
// unregisterReceiver(mReceiver);
super.onPause();
}
Service:
public class AppServiceDay extends Service {
CountDownTimer cdt;
public static Handler mHandler;
int downer = 1000;
int time = 100;
int mainTime = 100000;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
cdt = new CountDownTimer(mainTime, downer) {
#Override
public void onTick(long millisUntilFinished) {
time -= 1;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
broadcastIntent.putExtra("Time", time);
sendBroadcast(broadcastIntent);
}
#Override
public void onFinish() {
time = 100;
this.start();
}
};
cdt.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
onStartCommand is triggered everytime startService is called and in onStartCommand you are creating new countdown object,
Add a null check before creating new countdown object it will fix your duplicate timer running at same time.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
If(cdt == null) {
cdt = new CountDownTimer(mainTime, downer) {
#Override
public void onTick(long millisUntilFinished) {
time -= 1;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
broadcastIntent.putExtra("Time", time);
sendBroadcast(broadcastIntent);
}
#Override
public void onFinish() {
time = 100;
this.start();
}
};
cdt.start();
}
return super.onStartCommand(intent, flags, startId);
}

Android : How can I get int value form service and set in text View on activity

My app has a countDown timer for 24 hours in his service. And show time in TextView any time even user left the app.
On service, i put an int number = 5184000. this is 24 hours converted to milliseconds;
Problems:
TextView don't show time in Activity.
I want to when timer equals 00:00:00, timer reset and new time equals 23:59:59.
MainActiviy:
public class MainActivity extends Activity {
TextView tv;
BroadcastReceiver broad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Intent intent = new Intent(this, MyService.class);
startService(intent);
registerReceiver(broad, new IntentFilter(MyService.BROADCAST_ACTION));
broad = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = getIntent();
Bundle bundle = intent1.getExtras();
if (bundle != null) {
int data = bundle.getInt("DDDD");
tv.setText(data);
} else {
tv.setText("00:00:00");
}
}
};
}
Service:
public class MyService extends Service {
CountDownTimer cdt = null;
Intent intent1;
int h = 5184000;
public static final String BROADCAST_ACTION = "com.example.service";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i("DDD", "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("TIME", "Starting timer...");
cdt = new CountDownTimer(h, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i("TIME", "secondes: " + millisUntilFinished);
intent1 = new Intent(BROADCAST_ACTION);
intent1.putExtra("T", h);
sendBroadcast(intent1);
}
#Override
public void onFinish() {
Log.i("TIME", "Timer finished");
}
};
cdt.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
xml:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="134dp"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceLarge" />
You can use Alarm Manager for that.
Check out below links for AlarmManager.
AlarmManager
Scheduling Repeating Alarms

CountDownTimer inside Service stopped after application killed - Android

I'm new to services and BroadcastReceiver so maybe this question is newbie, but I didn't found the solution for my question after a long search on the web.
I need to run a CountDownTimer inside service, so the time keep moving even the application was finished.
In my code I based on THIS EXAMPLE.
My code works fine, but after the application is finished the CountDownTimer stopped(The service doesn't destroyed, just the timer).
I tried to implement it in different ways, but nothing works for me.
This is the part of my code that relevant:
AlarmReciver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
Bundle bundle = intent.getExtras();
background.putExtra("time", bundle.getInt("time"));
context.startService(background);
}
}
BackgroundService :
public class BackgroundService extends Service {
private final static String TAG = "BroadcastService";
private CountDownTimer cdt = null;
private Bundle bundle;
private boolean isRunning;
private Context context;
private int timeInMili;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
}
#Override
public void onDestroy() {
//cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
bundle = intent.getExtras();
timeInMili = bundle.getInt("time");
if(!this.isRunning) {
this.isRunning = true;
}
cdt = new CountDownTimer(timeInMili, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
stopSelf();
}
};
cdt.start();
return START_STICKY;
}
}
MainActivity (extends FragmentActivity):
public void StartBackgroundAlarm(int timeInMili)
{
Intent alarm = new Intent(this, AlarmReceiver.class);
alarm.putExtra("time", timeInMili);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pendingIntent);
}
MANIFEST :
<service android:enabled="true" android:name= "com.MES.yo.servicemanager.BackgroundService" />
<receiver android:name="com.MES.yo.servicemanager.AlarmReceiver"></receiver>

StartService returns null Android Service

I need to start a countdowntimer in backgroud service and show it on My fragment. This is where I am currently.
ComponentName c is null after calling startService.
I am not sure how I can debug this using debugger.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_map, container, false);
setUpMapIfNeeded();
controlv = rootView.findViewById(R.id.controls_parked);
parker_info = (TextView)rootView.findViewById(R.id.parked_info);
take_to_car_btn= (Button)rootView.findViewById(R.id.walk_to_Car);
unPark = (Button)rootView.findViewById(R.id.un_park);
timer = (Button)rootView.findViewById(R.id.timer_btn);
myContext = getActivity();
mDpi = getActivity().getResources().getDisplayMetrics().densityDpi;
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ComponentName c = getActivity().startService(new Intent(getActivity(), TimerService.class));
Log.i(TAG, "Started service");
}
});
return rootView;
}
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
private void updateGUI(Intent intent){
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
}
Toast.makeText(myContext, "Timer", Toast.LENGTH_SHORT).show();
}
This is my Service :
public class TimerService extends Service {
private final static String TAG = "TimerService";
public static final String TIMER_BR = "parking.group6.csc413.projectmap_timer";
Intent timer_intent = new Intent(TIMER_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
timer_intent.putExtra("countdown", millisUntilFinished);
sendBroadcast(timer_intent);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And yes my manifest file has:
<service android:name=".TimerService"/>
ComponentName is not null only if the Service was already started or is already running. If the service doesn't exist yet, null is return. To start your CountDownTimer, you can use an action:
Intent intent = new Intent(getActivity(), TimerService.class);
intent.setAction("START");
getActivity().startService(intent);
when onStartCommand is invoked, check if the action is equals to START. If it is, start your CountDownTimer
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ("START".equals(intent.getAction()) {
// start CountDownTimer
}
return super.onStartCommand(intent, flags, startId);
}

Categories

Resources