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"));
}
Related
I have a service that runs a timer on the background and I want that data to be passed to my fragment to show the timer there too. If i closed my app and open it again i want to see my edittext to show the timer. Any answer would be appreciated.
this is my service
public class MyService extends Service {
private Vibrator v;
//private static Timer timer = new Timer();
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);
}
#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();
}
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());
}
}
and here is the fragment. I'm planning on removing the countdown timer on this fragment since I'm going use the timer on the service.
public class page2 extends Fragment {
private static final String TAG = "page2";
private Button btntest;
private TextView timer,tv;
private Spinner spinner, spinner2;
public int hours, mins, duration;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page2_fragment,container,false);
btntest = (Button) view.findViewById(R.id.button2);
timer = (TextView) view.findViewById(R.id.Timer);
tv = (TextView) view.findViewById(R.id.textView3);
//setting up 2 spinners
spinner = (Spinner) view.findViewById(R.id.spinner1);
String [] values = {"00","01","02","03","04","05","06"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
spinner2 = (Spinner) view.findViewById(R.id.spinner2);
String [] values2 = {"00","01","10","20","30","40","50","60"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this.getActivity(), 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);
}
});
return view;
}
//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 = getActivity().getSharedPreferences("Timer", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("duration", d);
editor.apply();
Intent intent = new Intent(getActivity(),MyService.class);
getActivity().startService(intent);
Toast.makeText(getActivity(), "Intent passed and preferences saved!"+d,Toast.LENGTH_SHORT).show();
}
}
Thanks in advance.
Try EventBus library, you can send message as normal or stick event, maybe it can solve your problem :)
There are many ways you can update editText in your case.
When you open your application you can bind to your already running service. After binding you can call methods in service to get the results. For simple bind service refer bind service
You can keep a shared preference and continue updating it every countdown. Whenever app opens read the shared preference and update your edittext.
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 am starter in android. I want to create a Service.java from this Activity.class.
In my MainActivity I have 2 buttons(aBTN and bBTN). with clicking on each of them Adult1Activity with timer starts. this timer controls with PlayBTN and StopBTN. Also, I want to show timer in notification. I want to use 2 other buttons "RestoreBTN" and "CloseBTN" for connecting between activity and notification.
I use CountDownTimer class for timer. but I don't know how I write
Textview
RestoreBTN
Note: "aBTN" and "bBTN" have different times. "aBTN" is 10 minutes and "bBTN" is 5 min.
This code is the first one.
public class Adult1Activity extends AppCompatActivity implements View.OnClickListener{
private Button playBTN,stopBTN ; // contoroll buttons
private Button OnStop;
private TextView tv ;
private Toolbar toolbar;
private CountDownTimer countDownTimer;
private int total;
private long timeBlinkInMilliseconds ; // start time of start blinking
private boolean blink; // controls the blinking .. on and off
public CustomDialogClass cdd; // back dialog
private boolean isRunning = false;
public String timeString;
public NotificationManager notificationManager;
public NotificationCompat.Builder notificationBuilder;
public final int notification_id=01;
private static final String EXTRA_NOTE = "NOTE";
private static final String NOTE_RESTORE = "restore";
private static final String NOTE_CLOSE = "close";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adult1);
//define toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
playBTN = (Button) findViewById(R.id.play);
stopBTN = (Button) findViewById(R.id.stop);
tv = (TextView) findViewById(R.id.TimeCount);
playBTN.setOnClickListener(this);
stopBTN.setOnClickListener(this);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
handleIntent(getIntent());
}
#Override
public void onClick(View v) {
switch(v.getId())
{ case R.id.play:
tv.setTextAppearance(getApplicationContext(),
R.style.normalText);
setTimer();
stopBTN.setVisibility(View.VISIBLE);
playBTN.setVisibility(View.GONE);
startTimer(total);
break;
case R.id.stop :
countDownTimer.cancel();
Intent reloadIntent = new Intent(Adult1Activity.this, Adult1Activity.class);
startActivity(reloadIntent); // refresh activity
finish();
isRunning = false;
notificationManager.cancel(notification_id);
break;
}
}
//------------------------------------------------
private void setTimer() {
int time=30;
total = time*60 * 1000; // 30*60 aeconds
timeBlinkInMilliseconds = 10 * 1000;
}
private void startTimer(long enter) {
countDownTimer = new CountDownTimer(enter, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
final long seconds = leftTimeInMilliseconds / 1000;
long save = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
tv.setTextAppearance(getApplicationContext(),
R.style.blinkText);
// change the style of the textview .. giving a red
// alert style
if (blink) {
tv.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
tv.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
// format the textview to show the easily readable format
timeString = String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60);
tv.setText(timeString);
ExtendedNotification(timeString);
}
#Override
public void onFinish() {
Adult1Activity.this.finish();
vibrate(1000);
notificationManager.cancel(notification_id);
// turn on screen
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
// *********** notification
PendingIntent i = PendingIntent.getActivity(getBaseContext(), 0,
new Intent(getBaseContext(), Sport2Activity.class),0);
finish();
}
}.start();
}
//----------------------------------------------------------
public void onFinish() {
moveTaskToBack(true);
}
//-------------vibrate---------------------------------------------
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
//****************************************************
//alert dialog for back btn
public void onBackPressed () {
cdd = new CustomDialogClass(Adult1Activity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
}
public class CustomDialogClass extends Dialog {
public Activity c;
public Button minimizeBTN, exitBTN;
public CustomDialogClass(Activity a) {
super(a);
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.back_btn);
minimizeBTN = (Button) findViewById(R.id.minimizing_app);
exitBTN = (Button) findViewById(R.id.exit_completely);
minimizeBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MinimizeApp();
isRunning = true;
ExtendedNotification(timeString);
cdd.dismiss();
// notificationManager.notify(notification_id,notificationBuilder.build());
}
});
exitBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CloseApp();
}
});
}
}
//*****************Notification class******
private void ExtendedNotification(String time) {
final Intent resultIntentRestore = new Intent(this, Adult1Activity.class);
resultIntentRestore.putExtra(EXTRA_NOTE,NOTE_RESTORE);
resultIntentRestore.putExtra(time,NOTE_RESTORE);
PendingIntent restoreIntent = PendingIntent.getActivity(Adult1Activity.this,
0, resultIntentRestore, PendingIntent.FLAG_UPDATE_CURRENT);
final Intent resultIntentClose = new Intent(this, Adult1Activity.class);
resultIntentClose.putExtra(EXTRA_NOTE, NOTE_CLOSE);
PendingIntent closeIntent = PendingIntent.getActivity(Adult1Activity.this,
1, resultIntentClose, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder = new NotificationCompat.Builder(Adult1Activity.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Stand Up!")
.setContentText(time)
.setAutoCancel(true)
.addAction(new NotificationCompat.Action(R.drawable.ic_note_restore, "Restore", restoreIntent))
.addAction(new NotificationCompat.Action(R.drawable.ic_note_close, "Close", closeIntent))
.setContentIntent(restoreIntent);
//final Notification notification = notificationBuilder.build();
//notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(notification_id,notificationBuilder.build());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); // Make sure to call super
handleIntent(intent);
}
private void handleIntent(Intent intent) {
final String a = intent.getStringExtra(EXTRA_NOTE);
if (a != null) {
switch (a) {
case NOTE_RESTORE:
tv.setText(timeString);
// tv.setText(intent.getStringExtra(timeString));
notificationManager.cancel(notification_id);
break;
case NOTE_CLOSE:
countDownTimer.cancel();
isRunning = false;
notificationManager.cancel(notification_id);
// Adult1Activity.this.finish();
break;
}
}
}
//**********************App statuse********************
public void MinimizeApp(){
moveTaskToBack(true); //hide
}
private void CloseApp(){
android.os.Process.killProcess(android.os.Process.myPid());// exit
notificationManager.cancel(notification_id);
}
}
this is my ForgroundService that I has written till now.
public class TimerService extends Service {
public CountingDownTimer countingDownTimer;
public static String total_time_string;
public static int totalSeconds;
public NotificationManager notificationManager;
public NotificationCompat.Builder notificationBuilder;
public final int notification_id=01;
private static final String EXTRA_NOTE = "NOTE";
private static final String NOTE_RESTORE = "restore";
private static final String NOTE_CLOSE = "close";
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
countingDownTimer = new CountingDownTimer(totalSeconds,500); //milliseconds , (500 means) onTick function will be called at every 500
//countingDownTimer = new CountingDownTimer(intent.getExtras().getInt(total_time_string),500); //milliseconds , (500 means) onTick function will be called at every 500
countingDownTimer.start();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
setupNotification();
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
countingDownTimer.cancel();
notificationManager.cancel(notification_id);
}
//******************************************************************
public class CountingDownTimer extends CountDownTimer{
final String timeString;
/**
* #param millisInFuture The number of millis in the future from the call
* to {#link #start()} until the countdown is done and {#link #onFinish()}
* is called.
* #param countDownInterval The interval along the way to receive
* {#link #onTick(long)} callbacks.
*/
public CountingDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
timeString = null;
}
#Override
public void onTick(long leftTimeInMilliseconds) {
// format the textview to show the easily readable format
final long seconds = leftTimeInMilliseconds / 1000;
timeString = String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60);
Adult1Activity.tv.setText(timeString);
// ExtendedNotification(timeString);
}
#Override
public void onFinish() {
startActivity(new Intent(this,Sport2Activity.class));
vibrate(1000);
// turn on screen
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
}
}
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
//****************Notification ********************
private void setupNotification() {
Intent notificationIntent_Restore = new Intent(this,Adult1Activity.class);
notificationIntent_Restore.putExtra(EXTRA_NOTE,NOTE_RESTORE);
notificationIntent_Restore.putExtra(countingDownTimer.timeString,NOTE_RESTORE);
PendingIntent restoreIntent = PendingIntent.getActivity(this,
0, notificationIntent_Restore, PendingIntent.FLAG_UPDATE_CURRENT);
final Intent notificationIntent_Close = new Intent(this, Adult1Activity.class);
notificationIntent_Close.putExtra(EXTRA_NOTE, NOTE_CLOSE);
PendingIntent closeIntent = PendingIntent.getActivity(this,
1, notificationIntent_Close, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Stand Up!")
.setContentText(countingDownTimer.timeString)
.setAutoCancel(true)
.addAction(new NotificationCompat.Action(R.drawable.ic_note_restore, "Restore", restoreIntent))
.addAction(new NotificationCompat.Action(R.drawable.ic_note_close, "Close", closeIntent))
.setContentIntent(restoreIntent);
startForeground(notification_id,notificationBuilder);
//final Notification notification = notificationBuilder.build();
//notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
// notificationManager.notify(notification_id,notificationBuilder.build());
}
private class OTPCountdown extends CountDownTimer {
/**
* #param millisInFuture The number of millis in the future from the call
* to {#link #start()} until the countdown is done and {#link #onFinish()}
* is called.
* #param countDownInterval The interval along the way to receive
* {#link #onTick(long)} callbacks.
*/
public OTPCountdown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
tvOTPCountdown.setText(getString(R.string.otp_expiration_msg, millisUntilFinished / 1000));
}
#Override
public void onFinish() {
showManualWrap();
}
}
// use like this
otpCountdown = new OTPCountdown(60000, 1000);
otpCountdown.start();
Just because you are starter in Android and someone didnt get time to answer your question doesn't mean you would downvote their accepted answer and boss over them. If you are not able to figure out whats going on with your code. Give time to other developers to see it again.
Moderator please look at this thread: How to set Service/StartForeground to work CountDownTimer properly
I called the stopService() method from the calling class when the calling activity exits, and the service does not stop. It keeps on running in the background and can thus be a hastle to the end user. Any help would be greatly appreciated..
Code:
public class MainActivity2 extends ActionBarActivity {
ListView listView;
static int cnt1=0;
static int bob=1;
RelativeLayout background2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
background2 = (RelativeLayout) findViewById(R.id.background);
int num = 0;
final ListView theListView = (ListView) findViewById(R.id.listView);
Intent calledActivity = getIntent();
final List pe = calledActivity.getExtras().getStringArrayList("Caller1");
String[] s = new String[pe.size()];
for (int i = 0; i < pe.size(); i++) {
s[i] = (String) pe.get(i);
}
final ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pe);
theListView.setAdapter(theAdapter);
final int cnt = 1;
Intent mIntent = new Intent(this, MyService.class);
mIntent.putStringArrayListExtra("Caller2", (ArrayList<String>) pe);
mIntent.putExtra("intCall",bob);
startService( mIntent);
theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s1 = String.valueOf(parent.getItemAtPosition(position));
pe.remove(s1);
if (pe.size() == 0) {
stopService(new Intent(MainActivity2.this, MyService.class));
Intent goback;
goback = new Intent(MainActivity2.this, MainActivity.class);
startActivity(goback);
}
((BaseAdapter) theAdapter).notifyDataSetChanged();
}
});
}
MY SERVICE CLASS:
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent arg0) {
return null;}
#Override
public void onCreate() {
Toast.makeText(this, "Congrats! Blocker Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(final Intent intent, int startId) {
int i=0;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = tasks.get(0);
String activityOnTop=ar.topActivity.getClassName();
Intent lockIntent = new Intent(MyService.this, LockScreen.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName componentInfo = tasks.get(0).topActivity;
if(!componentInfo.getPackageName().equals("com.example.epiclapser.noprocrastinate"))
{
startActivity(lockIntent);
Log.v("iwashere", "-- ACTIVITY --");
}
}
},
0,
1000);
Toast.makeText(this, "My Blocker Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
Docs say:
Each timer has one thread on which tasks are executed sequentially.
So I see you have a thread in your service.If you created a thread,you can not stop it until it does it's task,unless it has a task that involves a loop.In this situation,in loop condition,you can check if this thread received stop message(cancel) or not?And if is received,stop the loop.
Note to self:
Bro, put System.exit(0) in onDestroy() , after timer.cancel() & timer.purge()