send intent only if activity is already running - Android Software Development

Hello,
I have a service that is running at all times. When it receives a certain intent I want it to pass this along to an activity that I have so that the activity can be updated. However, I don't want to resume the activity if it is stopped/paused. If the activity is stopped, I want it to stay that way and then I'll just check my content provider when the user chooses to return to that activity. Sending this intent seems to automatically end up calling onStart and onResume and bring the activity back into focus. So I'm wondering if there is a way to only send the intent if the activity is already running. Also, if this is not possible, are there any other suggestions you guys have?
I figured there would some flag I could add to the intent to make it do what I want but I haven't found anything useful.
There's even a question about this in the developer.android.com faq but the answer is not very helpful.
How can I check if an Activity is already running before starting it?
The general mechanism to start a new activity if its not running— or to bring the activity stack to the front if is already running in the background— is the to use the NEW_TASK_LAUNCH flag in the startActivity() call.
Click to expand...
Click to collapse
Than you so much,
Samuel Maskell
Edit: Removed explanation as to why the post is somewhat vague. See below.

You drew so much more attention to your potentially "secret" project by saying all that. If you had just given your question with a little context and not mentioned all that people would understand it and answer without thinking anything of it

well I wrote the post and felt that it was a little vague so I added a sentence to explain why. I'm not trying to draw attention to it. I don't feel like the post is hard to follow at all but perhaps I will remove the stuff about the project and keep it solely about the problem.
And please don't take this the wrong. I feel like what I just said sounds really bitter but I'm just trying to explain myself.

Related

I am writing a program on my htc and have a problem with multithreading and timers

Hi I didn't know where I could get help on this topic but seeing as some of the guys in here have made such excellent programs I thought you might be familar with c# on windows mobile.
here is my problem.
I have a task I need to do every x seconds I want to be able to start and stop this repeating task immediately.
I have attempted to solve this by creating a class which holds the taks I want to do, in this class I have put a windows.forms.timer with the task as its timer.tick event. this task has a method called start() which sets the timer going.
to start the process in my main thread i create a new thread which creates an instance of my class(mentioned above) and calls its start method.
The problem is the tick event never seems to fire is this because its in a seperate thread to the one which has focus, is it because it doesnt have an asociated form?
is there a better way to do this?
I want an object I can create which I can call methods to start and stop a repeating task.
many thanks,
I hope some one can help.
(sorry if this is completely the wrong place to post this)
Have you set the timer.Enabled = true?
Instead of windows.forms.timer try system.threading.timer!
comparison of timer classes in .net
Why have you put this in a thread, so you can abort it midway through processing its tick event?
Is there a better way you could do this than adding the complexity of threads? Perhaps add a bool to you class and your tick event can check at safe points if it is false (and exit)?
My initial thought to the problem as you have outlined it is that your thread is finished after completing its Start() method, so the tick event never gets called (as the timer no longer exists). You would need to keep the thread alive (without interfereing with your timer).
Windows.Forms.Timer is a bad choice for this as it uses the calling thread - so if you add a System.Threading.Thread.Sleep() (or some other blocking action) to keep your thread alive, your timer wont work. System.Threading.Timer is a better choice as it uses its own thread.
Hi thanks so much for the info I will have a look at threading timers.
I have put it in its own thread so I can abort it early because each "tick" could be between 5-15 mins and the task takes between 1 second and 5 mins so I wanted to be able to make sure the task is started at regular intervals and have the ability to stop the process immediately.
I was just thinking that neither timers or using a bool will allow me to stop the process immediately, is it safe to use thread.abort? i.e. if part of the task is to update a field could it be stopped half way through and corrupt the data?
if it is unsafe is there a safe thread abort i.e. abort as soon as the thread has finished updating any fields or database records(this thread wont update database but its good to know)
also to the point you raised about the thread finishing when my start() method finishes I kept that going using a while loop and a bool i.e.
while(keepGoing)
{
}
this seemed like a really horrid thing to do but do I have any other choice?
I think my design is not good my app basically wants to start off this running process when it loads but needs to be able to interupt it when some data changes.
(as an extra question does any one know if sqlce 3.5 has built in thread safety or will I have to lock functions that access data in my database?)
Threads can be somewhat unpredictable. Thread.abort calls an exception, so as far as i know if you have something like
var1 = "blah";
that would finish - var1 would not be corrupt. But, if you were doing something more complicated such as your database example you cant be sure when it will cut you off. Of course, you can catch the ThreadAbortException, and do some checking if required.
As for your while loop, that almost certainly blocked the thread and is why your timer did not work. Windows forms timers are based around events and will not typically run while one of your methods is still working, unless it yields somehow. Infact, on a single cpu device like your phone that loop would probably block a System.Threading.Timer because while(true); results in 100% cpu usage.
This is a quick example of how I would impliment your timer requirement - mostly stolen from the msdn page on System.Threading.Timer.
Code:
private void ThreadMethod()
{
System.Threading.ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false);
int interval = 10 * 1000;
System.Threading.Timer timer = new System.Threading.Timer(new System.Threading.TimerCallback(timer_Tick), resetEvent, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
while (true)
{
resetEvent.Reset();
timer.Change(interval, System.Threading.Timeout.Infinite);
resetEvent.WaitOne();
DoStuffThatTakesOneToFiveMinutes();
}
timer.Dispose();
}
private void timer_Tick(object timerObject)
{
System.Threading.ManualResetEvent resetEvent = (System.Threading.ManualResetEvent)timerObject;
resetEvent.Set();
}
private void DoStuffThatTakesOneToFiveMinutes()
{
MessageBox.Show("hi");
}
ThreadMethod can just be directly called from your thread.
timer.Change starts the timer off. The Infinite means it is not a repeating timer.
resetEvent.WaitOne() simply waits for the event to be triggered. The nice thing about doing it that way is your processing is done by the calling method, and you can be sure at what point in your process. (Well, as much as you can with it all running inside a larger thread.)
Edit:
Infact, that timer.Dispose() is pointless as it will never get called. Probably a good idea to call it if you catch the threadabortexception though.
Also, I think var1 (first example) would simply not change, but im not sure. I dont think it would get corruped either way.
Thanks so much for this information it looks excellent. So if I want to tidy up some stuff on exit I see on msdn it says the finally block will exitcuted before exit or I could catch the abortexception as you suggest, where would I put this code would it be inside the threadMethod? or does it go somewhere else?
also imagine this example I am updating a record in my database, I throw the abort exception and it stops the process midway, is there a way in code to say ignor this exception and continue? i.e. when updating database i could set a bool and then check this bool in the finally or catch block and if its true say ignor this and continue and then outside my thread I could do a check on the thread to see if its still running if it is then i wait for x amount of time and try the abort again?
what would be a good way to notify the calling thread that the thread with the timer is still running as the isAlive property is not included as part of the compact framework, I suppose I could have a bool in the calling thread which the timer thread could change in the finally catch block when the abort exception is passed, but this would mean passing the calling thread to the called thread is there any problems doing this?
sorry this is quite a complicated situation I have made for myself, I really appreciate the help.
Im afraid we have hit the limit of my knowledge on threads and exceptions.
My thought was you could wrap the database parts in a try-catch, at least allowing you to handle the abort gracefully. As far as I know you can not continue the thread at the point it stopped - you can merely ignore it and carry on after the catch. Of course, exceptions are not meant to be used on a trial basis, they are more worst case.
Events may suit you a bit better, as they do not halt the flow. That way your thread could keep track anytime it is doing something important like database access - and the event would only close if safe.
You should be able to have your thread access a bool in the parent object, aslong as you are careful with synchronization. Making sure all parts that read/write to it use lock should be sufficient.
http://www.blackwasp.co.uk/CSharpEvents.aspx
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Thanks again isangelous,
I have thought that events would be a good idea but found them a little confusing, I will have another look and see if I can use them somehow.(thanks for the link)
btw I used the code you provided and tweaked it a bit to get my first problem working, i put the contence of the threadmethod inside a try block catch the abort exception and then call timer.dispose(), seems to work quite nicely so far, although I dont think i have managed to abort half way through a process, it always seems to be before or after but seeing as I dont use any of the variables after its stopped I assume all would be safe anyway.
to make the updating database part safer I was thinking that I would also put that in another thread and if its running when I send the abort exception I would wait until it is free and then stop the timer, what do you think? does sending an exception to a thread halt all its created threads as well? because if so my plan wont work.
btw im alomst 100% confident that actually calling abort using my app while it is updating is impossible but I dont want there to be a bug present I know about.
anyway thanks again you have given me loads of things to try.

[Q] Android app auto starts again when device rotated

Hello all,
I've written a simple audio player app and testing it in Samsung Galaxy S.
It is a simple app with can create playlist and some buttons to play the mp3 file.
However, there's a funny bug in it.
After starting the app, whenever I rotate the phone, the running app will launch another instance of the app. If I rotate again, another instance (3rd) would be started. So u can hear 3 copies of the same audio being played simultaneously.
What could be wrong with it?
Is there some code which can prevent program re-entry?
Thanks.
It's not a bug, that's the way andorid OS works. You need to account for this in OnCreate for your activity. I assume you are spawning off the actual playing of the MP3 in a thread or service. You need to check if the service is already running in OnCreate and attach, else spawn a new one.
Hello Gene,
How do I check if an activity is already running?
I could not find the answer on the android developer page (the topic on application fundamentals).
And no, I'm not converting it to a service yet as this is my first app.
Haven't explore service yet.
Thanks.
I read on another article, a simple way to prevent this is to add overwrite the onConfigurationChanged function
@Override
public void onConfigurationChanged(Configuration newConfig) {
//ignore orientation change
super.onConfigurationChanged(newConfig);
}
and modify the androidmanifest.xml
<activity android:name="selectCategories" android:configChanges="orientation|keyboardHidden"></activity>
But it still launch multiple instance of the app.
Thanks.
This is a good question and should be in an FAQ somewhere.
As already mentioned, changing the display orientation basically restarts your app. Read the Android dev page on Activity lifecycle for more info.
A short answer for your question is: the Bundle parameter for onCreate() will be null when your app is first run. When your app is paused and restarted, that Bundle will be non-null. You can store data in that Bundle by overriding onSaveInstanceState(), then check for that data in onCreate(). It's a good idea to learn how to do this (save/read app data on pause/restart). Once you start testing apps by rotating the display at various times, you'll find a lot of them FC at unexpected places.
This is indeed a topic that keeps surprising people who are new to android (ahem, like me 4-5 months ago ).
The solutions above are perfect, however in certain situations there's another trick that might make your life much easier. I suspect it won't help you in this case, but it might help others who tackle the problem and see this thread.
Certain applications, mainly games, should be fixed in a single orientation. I.E. you won't be playing angry birds on portrait - that game is locked to landscape, as it should be. In order to lock your activity in a certain orientation you add this attribute to the manifest under the Activity tag. So a standard activity might look something like that, combined with the ignore tag from the previous posts:
Code:
<activity android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden"
android:name="whatever">
The great thing about this combination is that your activity will not restart at all when the phone is rotated. Of course, for a standard activity you'd usually want to support both landscape and portrait, but if you need your app to be in a fixed orientation this is the way to go - no weird FCs or annoying bugs
Hi,
How do I check the bundle?
And also, what to do if the bundle is not null? Just return?
Thanks.
regards
r_p_ang said:
This is a good question and should be in an FAQ somewhere.
As already mentioned, changing the display orientation basically restarts your app. Read the Android dev page on Activity lifecycle for more info.
A short answer for your question is: the Bundle parameter for onCreate() will be null when your app is first run. When your app is paused and restarted, that Bundle will be non-null. You can store data in that Bundle by overriding onSaveInstanceState(), then check for that data in onCreate(). It's a good idea to learn how to do this (save/read app data on pause/restart). Once you start testing apps by rotating the display at various times, you'll find a lot of them FC at unexpected places.
Click to expand...
Click to collapse

Communication between Service & Activity

Hello
I want to create an Android App. In the last days i read a lot of Android API Documentations, Tutorials and "how do do's". Now I'm really confused, because on one hand, it's nice to have so many possibility, but on the other it confuses me, whats the best way to do it. So I played a little with Activity life-cycle.
Now I'm going to start to build my first 'real' App.
This App should download initial data from a Webservice, process these data with a database, download more data related to results from a database, save these data again to database, and make it accessible in the Acitvity.
So please correct me if I'm wrong from this point on:
I assumend that a Android Service is the best way, to process these Data in a background-worker-thread.
So far so good. So I read about the Android Handler which seems to be a pipeline, so Threads can work on the Handler message queue. I can Access the Service from within my MainActivity over the ServiceConnection.onServiceConnetcted where I recieve a simple Binder which gives me access to my Service. From there i can put Messages in the Message queue from the HandlerThread. But how I can tell my Acitivity from within the Service, that it has finished Processing and send the Data to it?
I read that I don't have to use AIDL since the Service is running in the same Process. But How can I do it then? I tried to call onBind() in the Service, hoping OnServiceConnected will be triggered in the Acitvity which initially Binds these Services, but it doesn't seem to work. I also tried to "hack" the Funktionality, by spending my Service a singleton member "MyMainActivity" with corresponing static setMainActivity(MyMainActivity activity), calling it in the ServiceConnector onServiceConnected, with the same result: Runtime Error
I even don't think I understand the functionality behind these HandlerThread.
will it loop infinitly waiting for HandlerMessages while draining the Battery, or is it on a wait() status since it recieves a message?
I read the Android API about Services but for me, it seems that they only describe to Access the Service from the Activity, and not the other way round.
If I call a method of my Service within my Activity over the ServiceBinder, which has a return value, but was started in another Thread in my Service, how will my Activity know that it processes finish? 'busy waiting' on a boolean member of my Service doesn't seem to be the way to go. If I do that, like I saw in a tutorial, I don't see a reason not to do the work in the Activity Thread itself.
I read also about an AsyncTask, but this doesn't seem to be practicable for me, because I have to do different work related to JSON Objects I get.
Please you expirienced Android guys: show me the way.
You probably don't need a full-fledged service if you just need a background thread. Services can run independent of an activity and reconnect, etc. If you don't intend for the thread to be stand-alone, then just use a class that implements Runnable. Since you seem to have a handle (no pun intended) on handlers, this won't be too hard. Just post a message to your handler from your thread to let the activity know what's going on.

Detect Package Launch

I am working on an application and I need to be able to have a service that can detect when applications are opened, and take action based on that.
I have looked everywhere, and have not found a way to do so. I have read documentation on broadcast receivers, intent handlers, I found nothing.
I did however, find an app that can do so. App Protector. It allows password protecting certain applications.
Can anybody please point me in the right direction?
Thanks!
this is actually a very good question. a BroadcastReciever only gets Intents directed at it, and wouldnt see Intents for other classes and Packages.
ill be very interested to know the answer
killersnowman said:
this is actually a very good question. a BroadcastReciever only gets Intents directed at it, and wouldnt see Intents for other classes and Packages.
ill be very interested to know the answer
Click to expand...
Click to collapse
Well I was looking for a BroadcastReceiver that was sent out by the system to indicate that an app was opened, but I did not come across anything.
this isnt possible.. to be able to monitor all intents would make android extremely insecure
http://groups.google.com/group/android-developers/browse_thread/thread/54ddc9d36a24d77b
but there are ways to know when an application is launched. you just have to be creative.
this will give you a list of all the applications running.
Code:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
however to know when an app is launched you would need a timed loop and then check between versions of the List to see if there is a new app. this would suck the juice and be inneficient
AppProtector seem to access the eventlog. maybe you could have a ContentObserver attached to the event log
http://developer.android.com/reference/android/util/EventLog.html
http://developer.android.com/reference/android/database/ContentObserver.html
killersnowman said:
this isnt possible.. to be able to monitor all intents would make android extremely insecure
http://groups.google.com/group/android-developers/browse_thread/thread/54ddc9d36a24d77b
but there are ways to know when an application is launched. you just have to be creative.
this will give you a list of all the applications running.
Code:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
however to know when an app is launched you would need a timed loop and then check between versions of the List to see if there is a new app. this would suck the juice and be inneficient
AppProtector seem to access the eventlog. maybe you could have a ContentObserver attached to the event log
http://developer.android.com/reference/android/util/EventLog.html
http://developer.android.com/reference/android/database/ContentObserver.html
Click to expand...
Click to collapse
Interesting.
I also found this:
Code:
String str = ((ActivityManager.RunningTaskInfo)this.am.getRunningTasks(1).get(0)).topActivity.getPackageName();
It's one of the things App Protector uses
It starts a new intent, pointing to their application, and passing the parameters of the package you tried to run
Take a look at Tasker it can defiantly do this.
rujelus22 said:
Take a look at Tasker it can defiantly do this.
Click to expand...
Click to collapse
He doesn't want it for scripting, but for use in his own program.
From something awesome

Intent filters

Ok so i used to be a very experienced actionscript user. But i recently wanted to get back into programming so im learning java now or rather trying to.
So im trying to understand the xml side of this so far and have some questions im hoping u guys can answer.
activities
So as i understand it an activity is a screen in an app. So for example the standard launcher on my phone has pages of apps on my main screens. Each one of those would be an activity? And then another activity for when i press the button to display all installed apps?
Have i understood that properly?
intent filters
This is where im getting confused. Ive googled it and read as much as i can find. As i read it, feel like someones explaining rocket science to a 5 year old.
The words component and instances is being thrown around enough that i got no clue whats even being said. What i have understood is it gives data to the activity.
So a best guess from my partwould be its telling it how the screens going to work or maybe like if theres going to be a button on it maybe. Or perhaps it means something different like just the properties sort of stuff like screen size or stuff of that nature.
As u guys can probably tell im confused beyond comprehension. I got no idea how good my grasp is of any of this. But if theres someone out there kind enough to dumb it down a bit so normal people can understand it. Id be very gratefull.
Bump
Bump
Hey,
unfortunately i cant answer your question. This is a part of android I don't understand too.
I think you should post your question again in the Question and Answer forum of XDA. http://forum.xda-developers.com/android/help maybe there is an developer who can help you.
Greetings
Thanks ill post there and see if it makes any difference
Android apps run in sandboxes. Consider a huge box partitioned into 'n' number of sections. Each partitions represent a place in android environment where app can reside. By sandboxing, app are given unique ID(UID) when they start a process. Only apps having same (UID) can access the app's resources so no malicious app can peek into the resources of other app.
If apps cannot see other resources, how could they communicate within apps? Thats where intent comes in. Intents are like post letters and android is the postman. You can either give:
1. Recipient address, here, the package name of the app for which the intent is to be sent and may include your data in the intent if there is any and the postman (android) delivers it to the right person (target app). This is also known as explicit intent because you know the target class to call
2. Intent filter - This is not as specific as the first one. Here, your app has to perform something using an external app but your app doesnt know of the other apps which could perform the action. So, this time it will go for a broadcast and say "Hey! I need to take a picture! All camera apps please come in" and the broadcast is sent by android which displays list of apps which respond to this broadcast. When the user chooses the app to perform the action, the app fires, performs the task for your app, return the data to your app in form of intent result.
To register an app to respond to this type of intent, the app specifies something called intent-filter in their manifest which says the android, in our example context "I can perform camera action". So next time intent for camera action is sent, the app is in the list of apps to perform action with. This type of intent in implicit intent as you let the android and user decide the app. You can also specify your own custom intent-filters apart from standard android ones.
vijai2011 said:
Android apps run in sandboxes. Consider a huge box partitioned into 'n' number of sections. Each partitions represent a place in android environment where app can reside. By sandboxing, app are given unique ID(UID) when they start a process. Only apps having same (UID) can access the app's resources so no malicious app can peek into the resources of other app.
If apps cannot see other resources, how could they communicate within apps? Thats where intent comes in. Intents are like post letters and android is the postman. You can either give:
1. Recipient address, here, the package name of the app for which the intent is to be sent and may include your data in the intent if there is any and the postman (android) delivers it to the right person (target app). This is also known as explicit intent because you know the target class to call
2. Intent filter - This is not as specific as the first one. Here, your app has to perform something using an external app but your app doesnt know of the other apps which could perform the action. So, this time it will go for a broadcast and say "Hey! I need to take a picture! All camera apps please come in" and the broadcast is sent by android which displays list of apps which respond to this broadcast. When the user chooses the app to perform the action, the app fires, performs the task for your app, return the data to your app in form of intent result.
To register an app to respond to this type of intent, the app specifies something called intent-filter in their manifest which says the android, in our example context "I can perform camera action". So next time intent for camera action is sent, the app is in the list of apps to perform action with. This type of intent in implicit intent as you let the android and user decide the app. You can also specify your own custom intent-filters apart from standard android ones.
Click to expand...
Click to collapse
Gave u a thanks fkr that very useful responce. Thank you. So if ive understood this right. If i want to take a picture for example the intent filter part basically calls out for an external app to perform the action. With intent filter so basically when an app asks u with that menu what app youd like to choose thats an intent filter? And implicent thats the same menu or android just chooses it for you? Im trying to picture it from the user-side
Recipient address seems straight forward. You know u need an app and what its called. So u dont even need the user to select anything.
scorpafied said:
Gave u a thanks fkr that very useful responce. Thank you. So if ive understood this right. If i want to take a picture for example the intent filter part basically calls out for an external app to perform the action. With intent filter so basically when an app asks u with that menu what app youd like to choose thats an intent filter? And implicent thats the same menu or android just chooses it for you? Im trying to picture it from the user-side
Recipient address seems straight forward. You know u need an app and what its called. So u dont even need the user to select anything.
Click to expand...
Click to collapse
Your understanding on implicit intent is correct. To make it even more short an precise,
An intent is an abstract definition of the operation to be performed by the app
Click to expand...
Click to collapse
When the target action is known, say you invoke a second activity of you app. You know the target action (the class name), that is your implicit intent. You decide what action to perform without user intervention here. Explicit usually needs user input for inter-app communication to take place.
Examples of few implicit intents:
Starting an activity
Starting a service
vijai2011 said:
Your understanding on implicit intent is correct. To make it even more short an precise,
When the target action is known, say you invoke a second activity of you app. You know the target action (the class name), that is your implicit intent. You decide what action to perform without user intervention here. Explicit usually needs user input for inter-app communication to take place.
Examples of few implicit intents:
Starting an activity
Starting a service
Click to expand...
Click to collapse
Ok cool. So recipient is when we choose the app. Intent is whwn they get a menu to choose it. And implicent is is when android chooses it for them.
Sounds simple enough. Thanks for all the help buddy
And would i be right in assuming that the actions we put in intent filters and the others in form it of stuff like when its triggered, how often and so forth?

Categories

Resources