Service terminates when app terminates - Java for Android App Development

I am currently trying to implement an app that has a service running until the user explicitly ends it via the app. I would like the service to remain on otherwise. My current problem is that whenever the app is removed from the recent apps, it terminates the service as well. I have tried using START_STICKY in my onStartCommand but it doesn't change anything.
Code:
public class TriggerService extends Service{
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
and here is my code for when I call the service:
Code:
public void startServ(boolean state){
editor = sp.edit();
if (state == true) {
startService(new Intent(currentActivity, TriggerService.class));
editor.putBoolean("service_status", true);
toast = Toast.makeText(currentActivity, "Service Running", Toast.LENGTH_SHORT);
toast.show();
} else {
stopService(new Intent(currentActivity, TriggerService.class));
editor.putBoolean("service_status", false);
toast = Toast.makeText(currentActivity, "Service Not Running", Toast.LENGTH_SHORT);
toast.show();
}
editor.commit();
}
EDIT: I tried adding
Code:
android:isolatedProcess="true"
to the manifest but it didn't help. I tried a few things that were recommended over here but so far no dice

Check this article, it also suggests a potential solution
http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/
And this open issue
https://code.google.com/p/android/issues/detail?id=63793

painlessDeath said:
Check this article, it also suggests a potential solution
http://www.androidpolice.com/2014/0...ated-background-services-a-fix-is-on-the-way/
And this open issue
https://code.google.com/p/android/issues/detail?id=63793
Click to expand...
Click to collapse
You are a god send. Tested the app on JB and the service stayed when I closed the app. Thank god.

Related

Timer not firing

I have a very simple app (my first Android app) that's not working as I expect and does not work as examples have shown. I have a brand new installation environment using Eclipse. My target device and Android 2.1 (API Level 7).
Very simple, I have an activity and a service. I'd like to start the service from the activity and have the service execute some code every couple of seconds. I have no problem getting the service to start, but the timer never seems to fire. For the service I have (relevant code)
Code:
private Timer timer = new Timer();
AT Override // the at sign is being blocked here so I've changed it to AT
public void onStart(Intent intent, int startid) {
Toast.makeText(MyService.this,"Starting", Toast.LENGTH_LONG).show();
}
public void onCreate() {
super.onCreate();
Toast.makeText(MyService.this,"One", Toast.LENGTH_LONG).show();
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
Toast.makeText(MyService.this,"Act", Toast.LENGTH_LONG).show();
}
}, 0, 3000);
}
Here the Toast shows "Starting" then "One", then nothing else... Any thoughts?

[Q] Handling ACTION_SCREEN in a widget

Hi,
I'm doing a widget that needs to be update on screen_on or on
user_present. As I'm not hable to register a BroadcastReceiver inside
the widget I'm doing it in a Service that is triggered by the widget
like this:
Widget.java:
Code:
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(context,
WidgetService.class).setAction(WidgetService.ACTION_WIDGET_START));
}
WidgetService.java:
Code:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
String action = intent.getAction();
Log.d(LOG_APP,"WidgetService onStart: "+action);
if (ACTION_WIDGET_STOP.equals(action)) {
this.unregisterReceiver(mReceiver);
stopSelf();
return;
} else if (ACTION_WIDGET_START.equals(action)) {
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
this.registerReceiver(mReceiver, filter);
return;
}
The problem is that when I try to register the receiver I get the
error that the service has leaked IntentReceiver because it was
already registered. Ive checked and no duplicate registration was done
in my code.
Do you have any idea what I'm overlooking?
Thanks,
PMD

[Q][SOLVED] PreferenceActivity as AppWidget Config

I have been using a hand built ListActivity as my AppWidget config Activity but to be honest it looks ****ty and doesnt fit in with the rest of the app. So i wanted to transition over to a PreferenceActivity. i made a stub of a PreferenceActivity that launches the layout just fine when it is the main activity. but when i try to change from my ListActivity to my PreferenceAcitivity i get no launching of PreferenceActivity when i launch my widget. all i get is my widget.
i did a refactoring of my xml files to change the instances of my ListActivity (GITextConfig) to my PreferenceActivity (GITextPreferences).
how can i use a PreferenceActivity as my config?
do i need to have a dummy Activity be the config with a button to launch the PreferenceActivity? cause that works just fine. its lame and shouldnt be that way... nvm that does not work... i just cant get a prefs activity to run from an appwidget
anyone? this is quite annoying... i know it can be done as other widgets like gmail unread count does this. at least it appears to have a preferenceactivity as the configuration
got it to work. i dont know what i was doing before but i think i had a little too much of a stub for it to work. after i implemented the appwidget id verification and created my PreferenceManger and overode the onBackPressed() method it seems to work.... happy and confused.
Code:
public class GITextPreferences extends PreferenceActivity {
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager localPrefs = getPreferenceManager();
localPrefs.setSharedPreferencesName("GITC_Prefs");
addPreferencesFromResource(R.xml.gitc_preferences);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
@Override
public void onBackPressed() {
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
}

[Q] Dialog out of Activity

Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
DoR2 said:
Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
Click to expand...
Click to collapse
You cannot do this. There is simply no feature for that. I have had that problem, too.
Use a Notification or a Toast message.
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
zalez said:
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
Click to expand...
Click to collapse
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
nikwen said:
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
Click to expand...
Click to collapse
If I start a transparent activity user can't see that it was started as I understand. Can you give code for broadcast receiver maybe I misunderstand something
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
zalez said:
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
Click to expand...
Click to collapse
I understood everything except the way how app switch between position before signal came and required activity with alert dialog in it. As I see this code initialize activity and alert dialog but don't contain switching that I need
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
I would use the AlertDialog.Builder class for compatibility.
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Zatta said:
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Click to expand...
Click to collapse
I agree, but if he wants to use a dialog, we help him to make one.
The bad thing about the dialog is that it will interrupt whatever the user is doing. This could be very annoying. And who wants to use an app which has annoying popups?
zalez said:
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Click to expand...
Click to collapse
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
DoR2 said:
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
Click to expand...
Click to collapse
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
nikwen said:
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
Click to expand...
Click to collapse
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
DoR2 said:
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
Click to expand...
Click to collapse
Could you please post your code?
nikwen said:
Could you please post your code?
Click to expand...
Click to collapse
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
DoR2 said:
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
Click to expand...
Click to collapse
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
nikwen said:
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
Click to expand...
Click to collapse
Doesn't help:
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
View view=new View(this);
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
nikwen said:
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
Click to expand...
Click to collapse
I finally made it!:victory: Here is code:
1) Call dialog:
Code:
NBeep.createDialog(NBeep.DIALOG_ERROR, context);
2) NBeep.java
Code:
public class NBeep extends Activity{
public final static int DIALOG_ERROR = 4;
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_ERROR:
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
alertDialog.setCancelable(false);
dialog = alertDialog;//new AlertDialog.Builder(this).setMessage("ERROR! This is a global dialog\n Brought to you by Sherif").create();
break;
default:
dialog = null;
}
return dialog;
}
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog(DIALOG_ERROR);
}
public static void createDialog(int dialog, Context context){
Intent myIntent = new Intent(context, NBeep.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}

CountDownTimer problem

Hello! I'm new to this forum. I'm developing an Android app, I have some problems with the functionality of a timer and I don't figure out why. I would need some ideas.
In my application I have 2 activities: one is with the levels of a game, where you can chose between them and the second one is with the game itself. In the second activity I have a CountDownTimer which tells me when the game must finish. I have a progressBar assigned to that timer.
CountDownTimer mCountDownTimer; -global variable
In onCreate I have:
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
@override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
@override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
I have also overriden the native back button from Android to go to the first activity, the one with the levels and there I try to stop the counter, but it doesn't seem to work at all. The counter doesn't stop, and the other functions don't work as well.
Here is the code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
return;
How could I solve this? Thank you so much!
Here is your problem:
CountDownTimer mCountDownTimer; -global variable
There are no global variables in Java, only instance variables. Since you didn't post your full code I'm going to make a few assumptions here...
public class myAwesomeTimerClass {
CountDownTimer mCountDownTimer;
// bla bla
}
Then in your second activity/class, you should refer to the class:
instead of:
mCountDownTimer.cancel();
try:
myAwesomeTimerClass.mCountDownTimer.cancel();
Good luck.

Categories

Resources