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);
}
Related
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);
}
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
I have to write an Android background service which never stops and keeps my variables alive.
Here is my service:
public class PollingService extends Service {
public static final String TAG = PollingService.class.getSimpleName();
public static int alap = 0;
public PollingService() {
}
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "BIND");
return null;
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "UNBIND");
return true;
}
public class MyBinder extends Binder {
public PollingService getService() {
return PollingService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
alap = alap+1;
Log.d(TAG, ": "+alap+"");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "DESTROY");
}
}
This is a counter service and it works well when my app is running, but when I close the app my variable "alap" start counting again from zero.
I bind and unbind when I navigate from an Activity to another, but I need my variables values when I close the app.
The only way is to use the method startForeground() in your service. Try something like this:
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, new Notification());
Try to store your variable value in "SharedPreference" in onDestory function.
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
alap = sharedpreferences.getString("alap",null);
alap = alap+1;
Log.d(TAG, ": "+alap+"");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
return START_STICKY;
}
#Override
public void onDestroy() {
//storing data
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("alap", alap);
editor.commit();
Log.d(TAG, "DESTROY");
}
I am sending a Broadcast from my Service and trying to receive in my Activity but I don't see it receiving. Can someone suggest if I am doing something wrong. I am seeing onResume getting called but don't see flag
Log.d("InchooTutorial", msg_for_me);
getting logged.
Service Code :
Intent sendableIntent = new Intent("SOTGSAMReceiver");
sendableIntent.putExtra("kicked", prefs.getSurveySubmittedStatus(context));
LocalBroadcastManager.getInstance(AcrService.this).sendBroadcast(sendableIntent;
Activity Code :
// Get Broadcast
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("InchooTutorial", "Inside onResume");
IntentFilter intentFilter = new IntentFilter("SOTGSAMReceiver");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// extract our message from intent
String msg_for_me = intent.getStringExtra("kicked");
// log our message value
Log.d("InchooTutorial", msg_for_me);
}
};
// registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
If you are using LocalBroadcastManager to send broadcast you need to register with it.
Write for register:
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
And for unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(this.mReceiver);
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.sixmod.com.sixmod.MyReceiver";
Intent bi = new Intent(COUNTDOWN_BR);
Intent ci = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(180000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
ci.putExtra("countdownFinish", 1);
sendBroadcast(ci);
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 arg0) {
return null;
}
}
In Activity
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.e("Receiver Registered", "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(br);
Log.e("Unregistered", "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
getActivity().unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {// here you fetch the data
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>