Stop CountDownTimer when we click on the home button - java

How do I stop the CountDownTimer when I leave the application (when I click on the home button on my smartphone) the CountDownTimer remains running
  I tried with this code but when I leave the application a message appears in my smartphone "app name has stopped." Close the application
help me please
here is the code that I use
CountDownTimer timer = new CountDownTimer(120000, 1000) {
#SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
tv.setText(String.format("%d : %d ",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_cum, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smile_lost);
message.setText("You have exceeded \n your time of reflection");
builder1.setPositiveButton("Replay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}.start();
}
is the code in onStop ()
#Override
public void onStop() {
super.onStop();
timer.cancel();
}

I suggest two way
1
Create global variable like
private isInForgrand = false;
And in onStop() or onPause() and onResume() change it
#Override
public void onStop() {
isInForgrand = false;
super.onStop();
}
#Override
public void onResume() {
super.onResume();
isInForgrand = true;
}
And in onFinish() check it
#Override
public void onFinish() {
if(isInForgrand){
//do what you want
}else{
//your app NOT in Forgrannd
}
2
You can cancel CountDownTimer in onStop()
#Override
public void onStop() {
super.onStop();
mCountDownTimer.cancel();
}

Related

Music stops on moving to another activity, while using background service to play music

I'm developing a game, I have used services to play music on all activities.
I want to stop the music when we hit the home key, it shouldn't stop playing music when moving from one activity to another.
public class backService extends Service {
private MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
mp.release();
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.all);
mp.setLooping(true);
mp.start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my main activity file
public class Home extends AppCompatActivity {
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hide();
setContentView(R.layout.activity_home);
Intent i = new Intent(this, backService.class);
adv();
}
#Override
protected void onResume(){
super.onResume();
Intent i = new Intent(this, backService.class);
startService(i);
}
#Override
protected void onStop() {
super.onStop();
Intent i = new Intent(this, backService.class);
stopService(i);
}
#Override
protected void onDestroy(){
super.onDestroy();
Intent i = new Intent(this, backService.class);
stopService(i);
}
}
How can I stop the music when I hit the home key and keep playing the music when we switch between other activities
TIA
Please remove the stopService(i) inside onStop() method in Activity coz whenever you are going one Activity to Another Activity then onStop() method will be called, that's why your service is killing.
If you want to pause or stop music while press home button then implements ComponentCallbacks2 interface to Activity like this
#Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
if(mService != null){
mService.pauseMusic();
}
}
}
Try to stop the service in
#Override
public void onPause()
{
super.onPause();
// Check if app is in foreground
if(!isAppOnForeground(context))
{
stop music here
}
}
below is the method to check if the app is in foreground or not . just replace your package here "your package name here";
public static boolean isAppOnForeground(Context context)
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = "your package name here";
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}

Timer countdown in Android

Im new to android application development, sorry if i had made any mistakes. How can i start the timer countdown each time when i visit homeActivity as per my code.I appreciate everyone who tried to help me. Thank you.
public class homeActivity extends AppCompatActivity {
private TextView userEmail; // Declaring email textview
private TextView timerDisplay; // Declaring Timer Display textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userEmail = (TextView) findViewById(R.id.userEmailID);
timerDisplay = (TextView) findViewById(R.id.timer);
// Retriving the the email id of the user which was passed from the sigin Activity
userEmail.setText(getIntent().getExtras().getString("Email"));
//use of a timer to display the notification 40 seconds as default for testing purposes
new CountDownTimer(40000, 1000) {
public void onTick(long millisUntilFinished) {
// Displaying the following timer on the textview
timerDisplay.setText("seconds remaining: " + millisUntilFinished / 1000);
}
//once the timer stops the following notification message is being Displayed
public void onFinish() {
final String title1="Break!";
String subject1="It is time to take a break";
String body1="20 minutes have passed";
// Break taken is displayed on the textview
timerDisplay.setText("Break Taken");
// notification is diplayed
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle(title1).setContentText(body1).
setContentTitle(subject1).setSmallIcon(R.mipmap.iclauncher).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
}.start();
}
// Directed to rate us Activity
public void rateusOperation (View v){
Intent intent = new Intent(homeActivity.this,rateUsActivity.class);
startActivity(intent);
}
// Directed to daily offers Activity
public void dailyOffersOperation (View v){
Intent intent = new Intent(homeActivity.this,dailyOffersActivity.class);
startActivity(intent);
}
// directed to statistics Activity
public void statisticsOperation (View v){
Intent intent = new Intent(homeActivity.this,statisticsActivity.class);
startActivity(intent);
}
// directed to privacy policy Activity
public void privacyPolicyOperation (View v){
Intent intent = new Intent(homeActivity.this,privacyPolicyActivity.class);
startActivity(intent);
}
// Directed back to sign in Activity
public void logoutOperation (View v){
AlertDialog.Builder altDial = new AlertDialog.Builder (homeActivity.this);
altDial.setMessage("Are You Sure ? ").setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(homeActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = altDial.create();
alert.setTitle("You want to Logout ");
alert.show();
}
}
public class homeActivity extends AppCompatActivity
{
private TextView userEmail; // Declaring email textview
private TextView timerDisplay; // Declaring Timer Display textview
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userEmail = (TextView) findViewById(R.id.userEmailID);
timerDisplay = (TextView) findViewById(R.id.timer);
// Retriving the the email id of the user which was passed from the sigin Activity
userEmail.setText(getIntent().getExtras().getString("Email"));
final CounterClass timer2 = new CounterClass(4000, 1000);
timer2.start();
}
// Directed to rate us Activity
public void rateusOperation (View v){
Intent intent = new Intent(homeActivity.this,rateUsActivity.class);
startActivity(intent);
}
// Directed to daily offers Activity
public void dailyOffersOperation (View v){
Intent intent = new Intent(homeActivity.this,dailyOffersActivity.class);
startActivity(intent);
}
// directed to statistics Activity
public void statisticsOperation (View v){
Intent intent = new Intent(homeActivity.this,statisticsActivity.class);
startActivity(intent);
}
// directed to privacy policy Activity
public void privacyPolicyOperation (View v){
Intent intent = new Intent(homeActivity.this,privacyPolicyActivity.class);
startActivity(intent);
}
// Directed back to sign in Activity
public void logoutOperation (View v){
AlertDialog.Builder altDial = new AlertDialog.Builder (homeActivity.this);
altDial.setMessage("Are You Sure ? ").setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(homeActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = altDial.create();
alert.setTitle("You want to Logout ");
alert.show();
}
public class CounterClass extends CountDownTimer
{
TextView conter;
public CounterClass(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
final String title1="Break!";
String subject1="It is time to take a break";
String body1="20 minutes have passed";
// Break taken is displayed on the textview
timerDisplay.setText("Break Taken");
// notification is diplayed
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle(title1).setContentText(body1).
setContentTitle(subject1).setSmallIcon(R.mipmap.iclauncher).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished)
{
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
timerDisplay.setText(hms);
}
}
}

How to stop timer of an activity from another activity

Right now I have an activity, let's say 'Activity A' that runs the Timer. It is to update my Firebase when the time is up.
timer.scedule(new TimerTask()){
#Override
public void run() {
notification();
Firebase areaRef = mAreaRef.child(bKey);
areaRef.addListenerForSingleValueEvent(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
checkData = dataSnapshot.child("data").getValue(Integer.class);
Integer addData = checkData+1;
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
},millis);
There will be a button at 'Activity B'. When the button is clicked, the timer at 'Activity A' must be stopped.
How do I do this?
There just can be only one "Activity" activated in the same time. Your 'Activity A' can be instead by a service. And then your problem is solved by 'Activity B' directly call service method to stop the timer when the button is clicked.
If your timer task really needs to be alive across activities, maybe you should consider use a Service instead of a timer in specified activity.
1.Change Timer to CountDownTimer call start() to begin call cancel() to stop.
How to notify Activity A to stop the CountDownTimer, you can change SharedPreferences to others way to deal with data notify
public class MainActivity extends AppCompatActivity {
CountDownTimer timer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
SharedPreferences sharedPreferences = getSharedPreferences("count", 0);
if (sharedPreferences.getBoolean("stop", false)) {
timer.cancel();
} else {
Log.d("tag", millisUntilFinished / 1000 + "");
}
}
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.start();
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
}
public class ActivityB extends AppCompatActivity {
Button mStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
mStop =(Button) findViewById(R.id.stop);
mStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("count",0);
SharedPreferences.Editor edit= sharedPreferences.edit();
edit.putBoolean("stop", true);
edit.apply();
}
});
}
}

Hide AlertDialog in specific activity

I have one Quote application. When I open the application's MainActivity, if there is new data updated on the server side, one AlertDialog is shown for going to SettingsActivity. It takes some time for appear so if the app is already on SettingsActivity, it is still showing the AlertDialog to go to SettingsActivity.
I want to prevent the AlertDialog from showing in SettingsActivity but continue showing in other activities. My code for AlertDialog is below. How can I do that?
public class UpdatesDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(UpdatesDialogActivity.this);
builder.setTitle("Download New Status");
builder.setMessage("There Are New Status Arrived. Push Download Button From Settings.");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(UpdatesDialogActivity.this, SettingsActivity.class);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
finish();
return false;
}
});
builder.show();
}
// ==============================================================================
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
You can go for an 'instanceof' check and see if the current activity is settings or else.
if(activity instanceof SettingsActivity){
//don;t show dialog
}else{
//show dialog
}
Hope this will help.

My onEvent() part of the File Observer method doesn't work

I have already scanned all of the related questons&answers here, but I still couldn't find the solution.
the service class file:
public class otser extends Service {
private WindowManager windowManager;
private ImageView chatHead;
#Override public IBinder onBind(Intent intent) {
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
FileObserver observer = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String file) {
event &= FileObserver.ALL_EVENTS;
if(event == FileObserver.CREATE){
Toast.makeText(getApplicationContext(), "screenshot taken",
Toast.LENGTH_LONG).show();
}
}
};
observer.startWatching(); // start the observer
Toast.makeText(getApplicationContext(), "service: OK",
Toast.LENGTH_SHORT).show();
}}
According to other posts, I double checked the path, via creating a file programatically, it does exist, and correct.
The Activity class:
public class Home extends Activity {
Button showChatHead;
Button stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
showChatHead = (Button) findViewById(R.id.gomb);
stopService= (Button) findViewById(R.id.gomb2);
showChatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
startService(i);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
stopService(i);
}
});
}}
The service class linked well, the last Toast message pops up, as a conclusion only the observer is being skipped.
Any ideas?
Thanks in advance!
newer release:
FileObserver fileObserver = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "method entered", Toast.LENGTH_SHORT).show();
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
The onEvent method is not entered, the "method entered" Toast didn't appear.
in documentation of the onEvent-Method is mentioned, that it will run at another thread and you should consider this. using a handler, the Toast message should appear, like this:
private Handler handler = new Handler();
#Override
public void onCreate() {
fileObserver = new FileObserver("path") {
#Override
public void onEvent(int event, String path) {
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(FileWatcher.this, "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();

Categories