How to run dynamic service in an Android app? - android

I am writing a code in Android code to create dynamic service or run-time service in Android app. I want to create one service and it will run two dynamic service internally , with the unique id. But i am not able to figure out how to do it? Please go though my sample code :
MyCode:
MainActivity.java
package com.example.multipleservice;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView timer1;
TextView timer2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer1 = (TextView) findViewById(R.id.timer1);
timer2 = (TextView) findViewById(R.id.timer2);
Calendar calendar1 = Calendar.getInstance();
Intent myIntent1 = new Intent(MainActivity.this, MyService.class);
myIntent1.putExtra("Id", "1");
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC, calendar1.getTimeInMillis(), pendingIntent1);
long tm1 = 0;
String ticket1 = "1";
SharedPreferences timer_saved1 = getApplicationContext().getSharedPreferences("TimerSave"+ticket1, 0);
long timerData1 = timer_saved1.getLong("timer"+ticket1, 0);
long timerValue1 = 0;
long diff_value1 = 36680;
if(timerData1!=0)
{
timerValue1 = timerData1*1000;
}
else
{
timerValue1 = diff_value1*1000;
}
tm1 = timerValue1;
RemainTime1 timera = new RemainTime1(tm1,1000);
timera.start();
Calendar calendar2 = Calendar.getInstance();
Intent myIntent2 = new Intent(MainActivity.this, MyService.class);
myIntent2.putExtra("Id", "2");
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent2,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent2);
long tm2 = 0;
String ticket2 = "2";
SharedPreferences timer_saved2 = getApplicationContext().getSharedPreferences("TimerSave"+ticket2, 0);
long timerData2 = timer_saved2.getLong("timer"+ticket2, 0);
long timerValue2 = 0;
long diff_value2 = 36880;
if(timerData2!=0)
{
timerValue2 = timerData2*1000;
}
else
{
timerValue2 = diff_value2*1000;
}
tm2 = timerValue2;
RemainTime2 timerb = new RemainTime2(tm2,1000);
timerb.start();
}
public class RemainTime1 extends CountDownTimer
{
public RemainTime1(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
timer1.setText(hr+" hr : "+min+" mins : "+sec+" sec ");
}
}
public class RemainTime2 extends CountDownTimer
{
public RemainTime2(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
timer2.setText(hr+" hr : "+min+" mins : "+sec+" sec ");
}
}}
MySerivce.java
package com.example.multipleservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyService extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
} }
MyAlarmService.java
package com.example.multipleservice;
import java.util.concurrent.TimeUnit;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.Toast;
public class MyAlarmService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onStart(Intent intent, int startId)
{
String ticket = intent.getStringExtra("Id");
SharedPreferences timer_saved = getApplicationContext().getSharedPreferences("TimerSave"+ticket, 0);
long timerData = timer_saved.getLong("timer"+ticket, 0);
long timerValue = 0;
long diff_value = 0;
if(timerData!=0)
{
timerValue = timerData*1000;
}
else
{
timerValue = diff_value*1000;
}
RemainTime timer = new RemainTime(timerValue,1000);
timer.start();
super.onStart(intent, startId);
}
public class RemainTime extends CountDownTimer
{
public RemainTime(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
}
} }
This is my above code , i am getting NullPointerException in getStringExtra section. I want to create two different timer and when i will close the application , but still the two timer should run in the service and when i will open the app again then i should see the updated timer value from the two clock.
Please help me out !!! Please suggest me some possible solution.

Related

Android: Stopwatch (Timer) in background Service

I want to make an android application that have punch in and punch out functionality. Scenario is when the user entered in an application it enters its task and press punch in button, When punch in button is press current date and time is saved in a local database and timer is running on background even i close an application but issue is it cannot run in background when i close an application and starts again timer starts from beginning.
How to figure out that my service is running and get that data?
MainActivity.java
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.activity_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, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.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));
}
#Override
protected void onStop() {
super.onStop();
intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service
{
private Intent intent;
public static final String BROADCAST_ACTION = "com.example.wajid.service";
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;
}
}
Why do you want to run a timer? Instead, simply save the check-in time in shared preferences. On check-out, the two can be compared and the relevant time calculated.
If you are worried that the user might try to manipulate the local device clock, then instead of getting the local time, you can use network time.

set notification alert every 24 hours android

I want to fire a local notification every 24 hours at a specific time say evening 6 o clock
i have refered this code
here
and
here
This is the code i am trying
package com.banane.alarm;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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 static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
Button bananaButton;
TextView notificationCount;
TextView notificationCountLabel;
int mNotificationCount;
static final String NOTIFICATION_COUNT = "notificationCount";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
mNotificationCount = savedInstanceState.getInt(NOTIFICATION_COUNT);
}
setContentView(R.layout.activity_main);
bananaButton = (Button)findViewById(R.id.bananaButton);
notificationCount = (TextView)findViewById(R.id.notificationCount);
notificationCountLabel = (TextView)findViewById(R.id.notificationCountLabel);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(NOTIFICATION_COUNT, mNotificationCount);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onNewIntent( Intent intent ) {
Log.i( TAG, "onNewIntent(), intent = " + intent );
if (intent.getExtras() != null)
{
Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
}
super.onNewIntent( intent );
setIntent( intent );
}
public void triggerAlarm(View v){
setAlarm();
bananaButton.setVisibility(View.GONE);
notificationCountLabel.setVisibility(View.VISIBLE);
notificationCount.setVisibility(View.VISIBLE);
notificationCount.setText("0");
}
public void setAlarm(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, alarmIntent, 0);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR, 18); // At the hour you wanna fire
alarmStartTime.set(Calendar.MINUTE, 00); // Particular minute
alarmStartTime.set(Calendar.SECOND, 0);
// alarmStartTime.add(Calendar.MINUTE, 2);
alarmManager.setRepeating(AlarmManager.RTC, alarmStartTime.getTimeInMillis(), getInterval(), pendingIntent);
//Log.i(TAG,"Alarms set every two minutes.");
}
private int getInterval(){
int seconds = 60;
int milliseconds = 1000;
int repeatMS = seconds * 1440 * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
updateUI();
}
public void cancelNotifications(){
Log.i(TAG,"All notifications cancelled.");
}
public void updateUI(){
MyAlarm app = (MyAlarm)getApplicationContext();
mNotificationCount = app.getNotificationCount();
notificationCount.setText(Integer.toString(mNotificationCount));
}
#Override
protected void onResume(){
super.onResume();
if(this.getIntent().getExtras() != null){
Log.i(TAG,"extras: " + this.getIntent().getExtras());
updateUI();
}
}
}
when try the code given in the example it works perfectly hwoever when i try to fire a notification i just wont show up what error

background services stop when the app is closed via the BACK button

A background service in Android stops running when the user exits the app using the BACK button. The same service works fine if the app is in foreground or in background (clicking the HOME button).
there are 3 cases:
Keep the app running: every 15 seconds a notification is shown (OK).
Put the app in background by clicking the HOME button: notifications keep showing (OK)
Click the BACK button (this closes the app): the background service is stopped and no more notifications are shown (BUG)
Expected behavior
Also in case #3, the notifications should keep running every 15 seconds.
my entire source is below
MainActivity.java
package com.example.service_demo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private TextView timerValue;
private Button startTimer;
private Button cancleTimer;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapview();
}
private void mapview() {
timerValue = (TextView) findViewById(R.id.timertext);
startTimer = (Button) findViewById(R.id.starttimer);
cancleTimer = (Button) findViewById(R.id.cancletimer);
startTimer.setOnClickListener(this);
cancleTimer.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
i = new Intent(this, SimpleService.class);
if (isMyServiceRunning()) {
Toast.makeText(getBaseContext(), "Service is running,",
Toast.LENGTH_SHORT).show();
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
startTimer.setEnabled(false);
} else {
Toast.makeText(getBaseContext(), "There is no service running",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
if (v == startTimer) {
startTimer.setEnabled(false);
i = new Intent(this, SimpleService.class);
startService(i);
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
} else if (v == cancleTimer) {
i = new Intent(this, SimpleService.class);
stopService(i);
timerValue.setText("00:00:00");
startTimer.setEnabled(true);
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String str = intent.getStringExtra("textval");
timerValue.setText(str);
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (SimpleService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
i = new Intent(this, SimpleService.class);
startService(i);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
System.exit(0); // system.exit(0) is mendatory for my app so it can't be
// removed
}
}
SimpleService
package com.example.service_demo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleService extends Service {
private NotificationManager mNM;
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
long basestart = System.currentTimeMillis();
Timer timer = new Timer();
long timeswap = 0L;
int secs = 0;
int mins = 0;
int hour = 0;
Intent intent;
String s;
public static final String BROADCAST_ACTION = "com.example.service_demo.MainActivity";
private int NOTIFICATION = 1;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(BROADCAST_ACTION);
Toast.makeText(this, "Service Started", 2000).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
timer.schedule(new RemindTask(), 0, 1000);
}
});
t.start();
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(NOTIFICATION);
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
Toast.makeText(this, "Service Stoped", 2000).show();
}
class RemindTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = System.currentTimeMillis() - basestart;
timeSwapBuff = timeswap;
updatedTime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedTime / 1000);
mins = secs / 60;
hour = mins / 60;
secs = secs % 60;
mins = mins % 60;
s = "" + String.format("%02d", hour) + ":" + ""
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs);
if (s.equalsIgnoreCase("00:00:15")) {
showNotification();
}
intent.putExtra("textval", s);
sendBroadcast(intent);
}
}
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = s;
// Set the icon, scrolling text and timestamp
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher,
text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, "Notification Label", text,
contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
In the method onStartCommand() of the service, return START_STICKY.
The service will continue to run until you explicitly call stopSelf() in the service or call stopService() from your activity.
Try implementing foreground service. foreground service
Foreground service displays notification and is never stopped.
Implement this code snippet in your service's onCreate().
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
This works for me:
notifyIntent.setAction(Intent.ACTION_MAIN);
notifyIntent.addCategory(Intent.CATEGORY_LAUNCHER);

How to run CountDownTimer in a Service in Android?

I want a service which runs a CountDownTimer and in every tick I want to show the countdown in a Activity and after some interval play a sound.
All the process are going fine in a single Activity but during incoming call the countdown not working that's why I want to do this using a Service.
Can anybody help me?
thanks in advance.
Update...
mCountDownTimer = new CountDownTimer(mTimerDuration, 1000) {
#Override
public void onTick(long millisUntilFinished) {
if (mTimerDuration > 0) {
mDurationCount += 1000;
showCountDown(
ActivityA.this,
(mSimpleDateFormat.format(mTimerDuration
- mDurationCount)));
if (mDurationCount == mTimerDuration) {
if (mRepeatTime > 1) {
startRepeatTimer();
}
finishTimer();
}
}
}
#Override
public void onFinish() {
}
}.start();
The easiest way is probably to create a broadcast receiver in your activity and have the service send broadcasts to the receiver. Here's a full listing for a service class with a simplified CountDownTimer.
package com.example.cdt;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "your_package_name.countdown_br";
Intent bi = new Intent(COUNTDOWN_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);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#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 arg0) {
return null;
}
}
And here are the relevant lines from a main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BroadcastService.class));
Log.i(TAG, "Started service");
}
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();
registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.i(TAG, "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(br);
Log.i(TAG, "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
stopService(new Intent(this, BroadcastService.class));
Log.i(TAG, "Stopped service");
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
}
}
You'll also need to define the service between the start/end application tags in your manifest file.
<service android:name=".BroadcastService" />
Download source code Android Countdown Timer Run In Background
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/et_hours"
android:hint="Hours"
android:inputType="time"
android:layout_marginRight="5dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_timer"
android:layout_above="#+id/btn_cancel"
android:text="Start Timer"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/btn_cancel"
android:text="cancel timer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_timer"
android:layout_centerInParent="true"
android:textSize="25dp"
android:textColor="#000000"
android:text="00:00:00"/>
</RelativeLayout>
Timer_Service.java
package com.countdowntimerservice;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
twoDatesBetweenTime();
}
});
}
}
public String twoDatesBetweenTime() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", str_testing);
fn_update(str_testing);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
}catch (Exception e){
mTimer.cancel();
mTimer.purge();
}
return "";
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish","Finish");
}
private void fn_update(String str_time){
intent.putExtra("time",str_time);
sendBroadcast(intent);
}
}
MainActivity.java
package com.countdowntimerservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
private void listener() {
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours<=24) {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
}else {
Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}

Timer in Background

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;
}
}
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
}
Kindly go through the link hope it will be helpful if you want to run timer in background Timer in background
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/et_hours"
android:hint="Hours"
android:inputType="time"
android:layout_marginRight="5dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_timer"
android:layout_above="#+id/btn_cancel"
android:text="Start Timer"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/btn_cancel"
android:text="cancel timer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_timer"
android:layout_centerInParent="true"
android:textSize="25dp"
android:textColor="#000000"
android:text="00:00:00"/>
</RelativeLayout>
MainActivity.java
package playstore.com.a02backgroundtimer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
private void listener() {
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours<=24) {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
}else {
Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Timer_Service.java
package playstore.com.a02backgroundtimer;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
twoDatesBetweenTime();
}
});
}
}
public String twoDatesBetweenTime() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data",""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", str_testing);
fn_update(str_testing);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
} catch (Exception e) {
mTimer.cancel();
mTimer.purge();
}
return "";
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish", "Finish");
}
private void fn_update(String str_time) {
intent.putExtra("time", str_time);
sendBroadcast(intent);
}
}
Once the app starts you need to mention the hours you want timer for ... Then also after killing the app when you restarts the app it will show the start time of the timer ... Now you customize you application a per your requirement .

Categories

Resources