Method not executing? - java

I am running a 20 second timer in the background of my app using a service. I want the service to call my GameOver class when it is done with it's timer. By the way, the user is constantly switching activities while the timer is running, but when it finishes, the user has to be taken to the game over screen no matter what. I have put a toast in the service, but that doesn't show up.
Here is my service:
Here is my Main Menu where I call the service:
Here is the manifest where I show the service:
Please let me know as to why the service or the timer aren't running. Thank you so much for all of your help, I really appreciate it! If you need any more code, just let me know and I will show you. Thanks!
:-)

Your toast is not showing because a Service can't directly manipulate the UI, such as showing toasts.
To do this from a service, you need to run the Toast code on the main thread. This can be done as such:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(TwentySeconds.this.getApplicationContext(), "Started!", Toast.LENGTH_SHORT).show();
}
});
Your CountDownTimer isn't working because you never start it. Very simple.
You create the CountDownTimer, but never call .start() on the object.
cdt.start();

After a few hours on this issue, I figured out my pathetic error:
I had the service declaration OUTSIDE of the '< application>' end tag.
facepalm
ALWAYS keep service declarations inside of tag

Related

i want reduce time.how to go the next activity without taking time. i have 12 j son running in Asyncktask

thanks you for help i cleared this using volley liabraries.
I have a app in which there are 12 AsyncTask, which are used to downloa data from server. I want to navigate to next activity on button click. When user click on button i am stopping or cancelling all AsyncTask, but this process leads to lagging or hang screen for 5 to 10 second before proceeding to next activity.
According to me, this is happening,because it is cancelling AsyncTask.Is there any better way to switch activity? i am swiching successfuly but hanging for some time.
Please try writing the code in a separate ui thread as follows:
new Handler().post(new Runnable() {
#Override
public void run() {
// start your new activity here
}
});
Try using background service class, so there won't be any lagging while switching activity.

Close app after some time in background

I'm looking for a way to close an android app after some time while the app has not been in focus. For example if the user open up an other app instead, the app should exit after 5 mins. I have tried using runnable and creating a thread. But those method don't seems to work while the app is in the background (maybe they are pause I'm not sure). So how do I close the app when it is not in focus?
For those who are wonder the reason I want to do this is that the app contains some sensitives data about the user so I want to be sure it is all cleared when they aren't using it.
Something like this might work:
A field inside activity class:
private Thread t = null;
Inside onResume():
if(t!=null) {
if(t.isAlive()) {
t.interrupt();
t.join();
}
t=null;
}
Inside onPause():
t = new Thread() {
public void run() {
try {
sleep(5*60*1000);
// Wipe your valuable data here
System.exit(0);
} catch (InterruptedException e) {
return;
}
}.start();
}
I recommend calling finish() in the onPause() or onStop() callbacks. A TimerTask will not survive onPause() and a Service does not appear, on face value, to give you options. Maybe you can start a service, sleep the thread the service runs on, then kill the processes your app has after the sleep timer expires.
Alternatively, you can just implement some security libraries to help secure the data from other apps.
Here is the Google Services link.
Get the process ID of your application, and kill that process onDestroy() method
#Override
public void onDestroy()
{
super.onDestroy();
int id= android.os.Process.myPid();
android.os.Process.killProcess(id);
}
Refer- how to close/stop running application on background android
Edit- Use this with AlarmManager
The fundamental problem with what you're trying to do is that your Activity may not exist in memory at all when it's "running" in the background. The Android framework may have destroyed the activity instance and even the process it was running in. All that exists may be the persistent state you saved in onSaveInstanceState(...) and a screenshot for the recent apps list. There may be nothing for you to get a reference to and kill.
Frank Brenyah's suggestion to call finish() in onPause() will prevent your activity from running in the background at all, but this is the closest you can get to what you want. You probably only want to do this when isChangingConfigurations() is false. But even when all your app's activities are finished, Android may keep the process and Application instance around to avoid recreating them later. So you may also want to use Bhush_techidiot's suggestion of killing the process. Do this in onPause() because the activity may be destroyed without a call to onDestroy().

how to terminate AsyncTask in Android?

I'm currently have an Android application with 3 activities.
Main activity:
Constantly polling a Xml file using AsyncTask and update UI using onPostExecute.
The AsyncTask is loop by:
Handler.postDelayed(runnableCode, Poll_internval);
Second Activity:
Does the same thing, pulling Xml using another AsyncTask and update UI using onPostExecute.
loop by :
Handler.postDelayed(runnableCode, Poll_internval);
How should i kill the AsyncTask as it is constantly looping?
Would like to kill it when ending this activity with finish();
There is no way to cancel the AsyncTask, even with cancel method.
You need to implement your logic for canceling the task manually, see this link :
How to completly kill/remove/delete/stop an AsyncTask in Android
You can use like:
Asyn mAsyn = new Asyn();
mAsyn.execute();
if(mAsyn.isCancelled()){
mAsyn.cancel(true);
}
There is provision,
you can remove async task in call back in handler, there is method
handler.removeCallbacks(runnable);
In Asynctask there is status, you have to develop logic and check status code.
AsyncTask statuc
In my project, i have same condition and i developed this kind of logic, it work in my code.
please check it.
Have a look at the androidannotations framework, that has support for running async tasks and also cancelling them. You can checkout the details here:
https://github.com/excilys/androidannotations/wiki/WorkingWithThreads#background]
Basically, all you need to do is annotate the method that needs to run in another thread with
#Background(id="cancellable_task")
void someCancellableBackground(String aParam, long anotherParam) {
[...]
}
where "id" is the id of the new thread. Then, to cancel it you just call
BackgroundExecutor.cancelAll("id");

Architecture for simple timer app

I am currently working on a very simple countdown timer app. I need some advice on the correct architecture for a timer which can both fire when the app is closed but also show the progress when the app is open.
What I had until now is a simple Handler which executes a Runnable every 100 ms to update the progress bar and call the handler again like this
// ...
// start the timer
tickHandler.postDelayed(runnable, 100);
// ...
private Handler tickHandler = new Handler();
private Runnable runnable = new Runnable(){
#Override
public void run() {
if(tick()){
tickHandler.postDelayed(this, 100);
}
}
};
Now I wanted to be able to have the Timer running even when the app is closed. I first thought about a Service but then discovered the AlarmManager class which seams to do the job and is much easier to use. However I not only want to be able to post a notification to the notification center but also want the app opened up again and showing that the timer has finished.
Can this be done with the AlarmManager or do I need to implement a Service? How would the architecture for this application look like in terms of where is the control passed from the Activity to the Service and more importantly back again?
Thanks for any hints!
I guess, the AlarmManager does exactly what you want:
Taken from Android AlarmManager
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
So you can register the Intent, which you want to start after the Timer has finished and show the user that the Timer has stopped. Therefore, the AlarmManager should do the trick!
Btw: Using a Service may also work but brings other implications. For example, your app would have to be started during boot phase, which would disable it to be installed on external storage. See Android Install Locations

how to schedule some code execution in android or: what exactly are daemon threads in android?

i'm currently working on an app for the android os that requires to fetch data from a remote server from time to time.
as this "update" should be carried out even when the actual frontend app is not running, i implemented a remote service that is started on system boot. now i need to schedule a timer to start the update.
is the "Timer"-class the right one for this job? and if "yes": what is the difference between a "normal" Timer() and one started as a "daemon" by Timer(true)?
http://developer.android.com/reference/java/util/Timer.html isn't very helpful with this :(
EDIT:
ok - i see there are much more methods to do this than i expected. to clarify:
i want to execute some code at a time that is specified.
this timer is used to trigger the execution of code 7 days in the future. (i.e., every week at a given weekday and time)
the code should run WITHOUT waking the phone up if it is "sleeping" (screen dimmed).
when running the code, no activity should be started. i.e. no app pops up on the screen.
the code that is executed should fetch some data from the internet. if at this time no internet connection is available, the timer should be set to sth like 30 minutes and then try again.
after completing the code execution, the timer will be set for the next interval which will be 7 days later.
the timer should be started at system boot, e.g., if i reboot the phone, the timer should determine the next date to execute the code and schedule the timer. this has to work without ANY user interaction!
when "sleeping", the thread/service/timer/whatsoever should not consume any system resources if possible...
what i need is pretty much a simple unix cronjob.
i think anyone here knows "newsrob" for android? what i want to realize is pretty much the same as the newsrob-updateservice.
Use AlarmManager. This allows you to set your schedule, then exit your components. Your code does not need to remain in memory and will be triggered when the alarm sounds.
i implemented a remote service that is started on system boot
Please don't do that just for a scheduled task. Use AlarmManager.
If you want the work to be done while the phone is asleep, you will need to use a _WAKEUP alarm type and perhaps use something like my WakefulIntentService to keep the device awake while the work is being done.
I recently had to develop an application following the same pattern.
Here is how I designed it:
I created a service started either explicitely by the frontend when enabling it through a configuration dialog, either started by a BroadcastReceiver waiting for the activation of network connectivity:
<receiver android:name=".notifications.MyReceiver">
<intent-filter>
<action android:name="android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
The service, when started, starts a new HandlerThread, and associates it with a Looper:
public class MyService extends Service {
private Looper serviceLooper;
private MyHandler serviceHandler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//Toast.makeText(this, "service started", Toast.LENGTH_SHORT).show();
HandlerThread thread = new HandlerThread("MyHandlerThread", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
serviceLooper = thread.getLooper();
serviceHandler = new MyHandler(this, serviceLooper);
// initial message
serviceHandler.sendMessage(Message.obtain());
}
#Override
public void onDestroy() {
serviceLooper.quit();
//Toast.makeText(this, "service stopped", Toast.LENGTH_SHORT).show();
}
}
When the network goes down or if the frontend disables it, the service is stopped, as well as the looper.
Now, in the MyHandler, I actually get the updates from the server when receiving messages.
public class MyHandler extends Handler {
private final Context context;
public MyHandler(Context context, Looper looper) {
super(looper);
this.context = context;
}
#Override
public void handleMessage(Message msg) {
// handle message and perform update
// ...
// try again 30 minutes
this.sendMessageDelayed(Message.obtain(), 1000 * 60 * 30);
}
}
The trick as you can see, is to send itself a delayed message to be handled 30 minutes later.
The advantage of this solution over using the AlarmManager is that the phone will NOT be forcibly woken up at a designed time, meaning it plays nicer with the phone resources if not needed.
Moreover, I don't start the service at boot time, only when there's an active internet connexion, and I stop it as soon as the connexion is gone.
It's been pretty efficient so far.

Categories