Activity has a method called getTaskId(). How do I know if this task id matches the task id of the Application task stack? - android-activity

I can get the app ID from my running activity via activity.getTaskId(). It will report back 185. If I go to another app, and start my activity from a share button, it will be placed IN THAT apps stack. If I do activity.getTaskId() it will report back 192 for example. I am assuming that an application process can only have one main task stack associated with it. How do I get that tasks ID? I want to be able to know "Hey I'm running outside of your apps task stack".
I contemplated doing this by polling the taskId the first time my activity is created and set that as a member variable to my Application Class, but if my app is killed, and then started first from another application, it will have the incorrect task id as the "AppTaskStackId". I haven't found any API for this.

A different approach might be to have both an exported and non-exported activity. The exported activity would simply be forwarded on to the non-exported activity, but with an extra denoting that it was started externally. And then when starting the activity internally, you always call the non-exported activity without that "isExternal" extra.
And then, in the non-exported activity, you can check for the existence of that extra to determine if the activity was started internally or externally.

The only way I could find to get even close to what you are trying to accomplish would be with the following code in, say, your Activity's onCreate:
ActivityManager m = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTaskInfoList = m.getRunningTasks(1);
if(!runningTaskInfoList.isEmpty()) {
String callingPackageName = runningTaskInfoList.get(0).baseActivity.getPackageName();
}
Here callingPackageName would be set to the package name of your app if the activity has been invoked from another activity in your own app, or is the main activity of your app.
However, if the activity was started by another app, say using the share function, then callingPackageName would be the package name of the calling app, so all you have to do is check if this is equal to your app's package name by calling getPackageName().
Also note that:
Your app will now need the android.permission.GET_TASKS permission
The documentation for this method states:
Note: this method is only intended for debugging and presenting task management user
interfaces. This should never be used for core logic in an application, such as deciding between
different behaviors based on the information found here. Such uses are not supported, and will
likely break in the future.
So I'm not sure how reliable this is or if it is even useful to you.

A recently (API 29) added TaskInfo:
https://developer.android.com/reference/android/app/TaskInfo
should help here.

Related

What is the correct process to switch between ADFs?

I have a project which lets the user to select from the ADFs existing on a Tango-enabled device, to allow them to correctly localize in a number of different spaces.
My code (Unity 5.5, C#, Farandole SDK) essentially performs manual Tango startup with a null AreaDescription as the entry flow. If the user then selects an ADF, I'm calling TangoApplication.Shutdown() then TangoApplication.Startup(newArea).
in Eisa, this works. In Farandole, I get a permissions failure.
if, using Farandole, I explicitly request permissions (after the Shutdown) and wait for the permissions response to come back before calling Startup, the system appears to re-localise against the new ADF, but the Tango system is re-registering callbacks every time around through Startup without unregistering them, meaning I get my callbacks called multiple times for each ADF that I switch to.
What is the correct process to switch between ADFs? Should a shutdown be required before calling Startup, and if so, what is the correct way to shutdown the TangoApplication to avoid multiple callbacks?
I am interested in this answer too. The way I would do it, is reload the scene with the new ADF, just like it is done in the AreaLearning example, so TangoManager and TangoPoseController are reset.

Android Async Task does not update UI when application is in background

The application I am working on downloads and parses a large xml file to populate UI elements, namely search and a spinner. This is done through an async task. If the user decides to switch out of the application during this, the information is downloaded correctly, but then when the application is resumed, the UI will not be updated.
Is this because the changes can't be made while the application is not active? What is the best way to go about checking whether the UI was not updated on resume? Or instead should I be doing something with the Async task, checking whether the UI thread is available? I'm having a hard time debugging this because it involves leaving the application which ends the debugger.
You can achieve this scenario through the broadcast receive.
Follow the step:
Solution 1:
Step 1;
Register the broadcast receiver before executing the Asyntask.
Step 2:
send Broadcast in onPostExecute method of Asyntask.
step 3:
And then you can able receive your broadcast message in your activity.
and do whatever you want.
Solution 2:
Otherwise you can use Interface Call back for this Scenario.
Hope It will help you.
It should'nt. App being in background means View objects may or may not be there. Actually the entire process may be stopped or just deleted by android.
Use a Service to truly do processing in background. When processing is complete but UI is not there, post a notification to let user know, OR, save the results and provide it to UI the next time it binds to your service and ask for same thing (a.k.a caching).
The application in background may not be live. The O.S may destroy it in case of memory constrains.
The trick is to try an alternate logic.
When the application moves from background to foreground onresume() is called ,you could try saving the data to db and update the content on the resume call.
FYI.onPause() and OnResume() is called when the application goes background and foreground respectively.

Best method to run a periodic background service in java blackberry

Objective: I want to develop an UI application that runs a service/ task/method
periodically to update database. This service should start after
periodically even if my application is not active/visible/user exits
app. Similar to an Android Service .
I'm using BlackBerry Java 7.1 SDK eclipse plugin .
The options I came across are the following:
1) How to run BlackBerry application in Background
This link suggests that I extend Application instead of UIApplication. But I can't do that as my application has a user interface.
2) Make application go in background
I don't want my UI application to go in background, instead i just want my application to call the service periodically .
3) Run background task from MainScreen in BlackBerry?
This link suggests to run I a thread, but I don't think that if user exits my application then the thread will run in background
4) Blackberry Install background service from UI application?
This suggests using CodeModuleManager ,whose usage I'm unable to figure .
Please suggest what is the best way to achieve this objective or suggests any other better method .
I am new to blackberry so please pardon my ignorance.
To expand on Peter's Answer:
You will need to create two classes :
class BgApp extends Applicaton
class UiApp extends UiApplication
I guess you have already created the class that extends UiApplicaiton. So add another class that extends Application.
Then create a class that extends TimerTask and implement its run method to call the method that updates the database.
class UpdateDatabaseTask extends TimerTask
In the BgApp constructor, create a Timer. And schedule the UpdateDatabaseTask using the schedule(TimerTask, long, long) method.
Define alternate entry points, check the "Do not show on homescreen" and "auto run on startup" checkboxes for the bgapp's entry point.
It is easiest and simplest to use the builtin persistence mechanism (PersistentStore and Persistable interface) for storing data. Even if you use any other means like RecordStore or SQLDb, both UiApp and BgApp can use access the same database. The values updated by the bgapp will be accessible by the uiapp and vice-versa, automatically.
If you want to send a signal from bgapp to uiapp (for example when bgapp downloads new data you want the uiapp to reload the data instantaneously), post a Global Event (ApplicationManager.postGlobalEvent()) when the download is complete and listen for it in the screen that is displaying the data (GlobalEventListener interface).
There are code samples for each of these available as part of the SDK or search on the internet and you'll find a lot of implementations.
Good research, lots of interesting thoughts.
I think the best thing to do is to try the simple standard approaches and only make something more sophisticated if you need to.
Here are two options that would be regarded as 'standard', with brief advantages and disadvantages:
a) Make your UiApplication go to the Background
Instead of exiting when the user presses the 'close' button, your UiApplication will "requestBackground()". it will automatically be bought to the foreground when the user clicks on the icon, or selects your application from the task switcher. Then you can run a Thread whenever you want or in fact leave one running to update the database.
This is my preferred method. But you have to careful with memory management to make sure there are no leaks. And some people don't like the idea that the Application is visible on the Task Switcher all the time.
b) Alternate Entry
With this option, your one Application package contains two Applications, or more accurately, one Application and one UiApplication. The UiApplication is run when the user clicks on the icon. The Application runs as a background task, and updates the database for your UiApplication.
This looks like a more elegant solution, but introduces some possible communication issues, and is more difficult to debug.
In your case, since you are relatively new to BB, I would suggest that you use option a, and if you find it doesn't work for you, you will not find it that difficult to swap to option b.
And to comment on the Options you have already presented:
Sort of covered with option b
Option a
You are correct - if an Application exits, all the Threads are killed
Leaves the problem of creating the application in the first place and then debugging it. This is not really a solution for you, more an implementation method.
The above is brief, please ask if it is not clear.
This might help with b:
http://supportforums.blackberry.com/t5/Java-Development/Set-up-an-alternate-entry-point-for-an-application/ta-p/444847
Edit:
Editing this to respond to the questions and to expand on the alternative answer, which expanded on this one (bit circular I know...).
To answer the second question first, I agree with the other answer which states the alternate entry (background) and the foreground app can share an SQLite database.
With respect to how these two communicate, while they work just fine, personally I am not a great fan of Global Events because they are propagated to all Applications on the BlackBerry. You can achieve similar things in many alternative ways - the trick is to find something that is common to both applications so that they can communicate. To this end, I recommend using RuntimeStore. See this KB article:
http://supportforums.blackberry.com/t5/Java-Development/Create-a-singleton-using-the-RuntimeStore/ta-p/442854
Regarding how you persist your database, I like PersistentStore because it is present on all devices. But if you really have a database, and not persistent Objects, then SQLite seems the ideal thing to use. Personally I would not use RecordStore, but here is a discussion of the options:
http://supportforums.blackberry.com/t5/Java-Development/Introduction-to-Persistence-Models-on-BlackBerry/ta-p/446810
And just a clarification - in the example given, you have two applications, BgApp and UiApp. You will only have one main() method. This main method will use the args that you specify to determine which one to start, which it will create and have it "enter the dispatcher". If I could make a recommendation - use "gui" as the argument to specify that you will start your UiApplication. I have experienced a circumstance that the OS attempted to start my alternate entry Ui application with this String, regardless of what I had actually specified. Might have been a one off, but I have stuck to doing that ever since.
Finally two comments on the use of Timers and Timertask to provide triggered events. The first comment to make is whatever you run in the TimerTask should not take that long - so you should just use the TimerTask to initiate the download Thread (which might take a long time). Secondly for me, in this situation, I would not use Timer/TimerTask. I would rather just have a single Thread, which 'waits', and then processes. The advantage to me is that this can be adaptive. For example, if you fail to connect, then you might shorten the time till the next connection attempt. Or if it is after hours, then you might lengthen the time between connections to reduce battery usage. Or you might stop connecting completely when the battery is very low.
Hope this helps.

Is there a sendToActivity() method?

I have a program with about 8 Activity classes, and 1 Application class. I want my Application class to be able to communicate with every Activity, but on its own terms. I don't want the activity to ask the Application for data, I want the Application to send the Activity data. The problem with this, is that depending on the current state of the program I'm unsure what Activity will be open.
Is there a method of some sort which will send information from the Application to the CURRENT activity?
The Application class connects with an embedded Bluetooth Device and needs to receive different pieces of data depending on which Activity the user is currently in. I originally had it as a regular class, which was initialized in the MainMenu of my program and passed a Handler. However, it seemed like weak design to pass that Handler from Activity to Activity time and time again.
You could use a Callback Method
Every Activity has it's own callback method and registers that method onResume() in the Application Class. (it's like an onApplicationWantsToDoSomethingWithMeListener() ;)
or why not a Service in background? instead of the Application, since what you want sounds like a Service. More details?
EDIT:
I made a similar application with bluetooth, you should definetly use a Service for that, but you can communicate with your service per Application. Say the Service calls the callback in the Application look here for an implementation uf such a thing

Why use the Bundle when you can just use the Application?

I'm reading this article on how to : correctly retain variable state in Android and I'm reminded that I've never gotten a good answer (and can't find one here) for why it's better to tussle with the Bundle (which isn't a HUGE hassle, but definitely has its limitations) rather than just always have an Application overridden in your App, and just store all your persistent data members there. Is there some leakage risk? Is there a way that the memory can be released unexpectedly? I'm just not clear on this... it SEEMS like it's a totally reliable "attic" to all the Activities, and is the perfect place to store anything that you're worried might be reset when the user turns the device or suspends the app.
Am I wrong on this? Would love to get some clarity on what the true life cycle of the memory is in the Application.
Based on the answers below, let me extend my question.
Suppose I have an app that behaves differently based on an XML file that it loads at startup.
Specifically, the app is a user-info gathering app, and depending on the XML settings it will follow an open ended variety of paths (collecting info A, but not J, and offering Survey P, followed by an optional PhotoTaking opportunity etc.)
Ideally I don't have to store the details of this behavior path in a Bundle (god forbid) or a database (also ugly, but less so). I would load the XML, process it, and have the Application hold onto that structure, so I can refer to it for what to do next and how. If the app is paused and the Application is released, it's not *THAT big a hassle to check for null in my CustomFlow object (that is generated as per the XML) and re-instantiate it. It doesn't sound like this would happen all that often, anyway. Would this be a good example of where Application is the *best tool?
The question as to which method is better largely depends upon what information you are storing and need access to and who (which components, packages, etc.) needs access to that information. Additionally, settings like launchMode and configChanges which alter the lifecycle can help you to determine which method is best for you.
First, let me note, that I am a huge advocate for extending the Application object and often extend the Application class, but take everything stated here in its context as it is important to understand that there are circumstances where it simply is not beneficial.
On the Lifecycle of an Application: Chubbard mostly correctly stated that the Application has the same life as a Singleton component. While they are very close, there are some minute differences. The Application itself is TREATED as a Singleton by the OS and is alive for as long as ANY component is alive, including an AppWidget (which may exist in another app) or ContentResolver.
All of your components ultimately access the same object even if they are in multiple Tasks or Processes. However, this is not guaranteed to remain this way forever (as the Application is not ACTUALLY a Singleton), and is only guaranteed in the Google Android, rather than the manufacturer overridden releases. This means that certain things should be handled with care within the Application Object.
Your Application object will not die unless all of your components are killed as well. However, Android has the option to kill any number of components. What this means is that you are never guaranteed to have an Application object, but if any of your components are alive, there IS an Application to associate it to.
Another nice thing about Application is that it is not extricably bound to the components that are running. Your components are bound to it, though, making it extremely useful.
Things to Avoid in Application Object:
As per ususal, avoid static Contexts. In fact, often, you shouldn't store a Context in here at all, because the Application is a Context itself.
Most methods in here should be static, because you are not guaranteed to get the same Application object, even though its extremely likely.
If you override Application, the type of you data and methods store here will help you further determine whether you need to make a Singleton component or not.
Drawables and its derivatives are the most likely to "leak" if not taken care of, so it is also recommended that you avoid references to Drawables here as well.
Runtime State of any single component. This is because, again, you are not guaranteed to get back the same Application object. Additionally, none of the lifecycle events that occur in an Activity are available here.
Things to store in the Application (over Bundle)
The Application is an awesome place to store data and methods that must be shared between components, especially if you have multiple entry points (multiple components that can be started and run aside from a launch activity). In all of my Applications, for instance, I place my DEBUG tags and Log code.
If you have a ContentProvider or BroadcastReceiver, this makes Application even more ideal because these have small lifecycles that are not "renewable" like the Activity or AppWidgetProvider and can now access those data or methods.
Preferences are used to determine, typically, run options over multiple runs, so this can be a great place to handle your SharedPreferences, for instance, with one access rather than one per component. In fact, anything that "persists" across multiple runs is great to access here.
Finally, one major overlooked advantage is that you can store and organize your Constants here without having to load another class or object, because your Application is always running if one of your components is. This is especially useful for Intent Actions and Exception Messages and other similar types of constants.
Things to store in Bundle rather than Application
Run-time state that is dependent upon the presence or state of a single component or single component run. Additionally, anything that is dependant upon the display state, orientation, or similar Android Services is not preferrable here. This is because Application is never notified of these changes. Finally, anything that depends upon notification from that Android System should not be placed here, such as reaction to Lifecycle events.
And.... Elsewhere
In regard to other data that needs to be persisted, you always have databases, network servers, and the File System. Use them as you always would have.
As useful and overlooked as the Application is, a good understanding is important as it is not ideal. Hopefully, these clarifications will give you a little understanding as to why gurus encourage one way over the other. Understand that many developers have similar needs and most instruction is based on what techniques and knowledge a majority of the community has. Nothing that Google says applies to all programmer's needs and there is a reason that the Application was not declared Final.
Remember, there is a reason Android needs to be able to kill your components. And the primary reason is memory, not processing. By utilizing the Application as described above and developing the appropriate methods to persist the appropriate information, you can build stronger apps that are considerate to the System, the User, its sibling components AND other developers. Utilizing the information that everyone here has provided should give you some great guidance as to how and when to extend your Application.
Hope this helps,
FuzzicalLogic
I prefer to subclass Application and point my manifest to that. I think that's the sane way of coding android although the Android architects from Google think you should use Singletons (eek) to do that. Singletons have the same lifetime as Application so everything that applies to them applies to Application except much less dependency mess Singletons create. Essentially they don't even use bundles. I think using subclass Application has dramatically made programming in Android much faster with far less hassle.
Now for the downside. Your application can be shutdown should the phone need more memory or your Application goes into the background. That could mean the user answered the phone or checked their email. So for example, say you have an Activity that forces the user to login to get a token that other Activities will use to make server calls. That's something you might store in your service object (not android service just a class that sends network calls to your server) that you store in your subclass of Application. Well if your Application gets shutdown you'll loose that token, and when the user clicks the back button your user might return to an Activity that assumes you are already authenticated and boom your service class fails to work.
So what can you do? Continue to use Bundle awfulness? Well no you could easily store security tokens into the bundle (although there might be some security issues with that depending on how this works for your app), or you have to code your Activities to not assume a specific state the Application is in. I had to check for a loss of the token and redirect the user back to the login screen when that happens. But, depending on how much state your Application object holds this could be tricky. But keep in mind your Application can know when it's being shutdown and persist it's internal state to a bundle. That at least allows you to keep your Objects in memory for 99% of the time your Application, and only save/restore when it gets shutdown rather than constantly serializing and deserializing with boiler plate code whenever you move between Activities. Using Application lets you centralize how your program can be brought up and shutdown, and since it normally lives longer than any one activity it can reduce the need for the program to reconstitute the guts of your App as the user moves between Activities. That makes your code cleaner by keeping out details of the app from every Activity, reduces overhead if your Application is already built, shares common instances/code, and allows Activities to be reclaimed without loosing your program all together. All good programs need a centralized hub that is the core, and subclassing Application gives you that while allowing you to participate in the Android lifecycle.
My personal favorite is to use http://flexjson.sourceforge.net/ to serialize my Java objects into bundles as JSON if I need to send objects around or save them. Far easier than writing to sqlite DB when all you need to do is persist data. And nice when sending data between two Activities using objects instead of broken apart primitives.
Remember by centralizing your model in the Application you create a place to share code between multiple Activities so you can always delegate an Activities persistence to an object in the Application by hooking the onPause() as well allowing persistence to be centrally located.
The short answer is: use bundles as it makes saving your state out when you're backgrounded easier. Also, it's complicated.
The long answer:
My understanding is, as soon as you Activity's onPause method is called (and onSaveInstanceState which gives you a bundle into which you should store your Activity's data) your process can be terminated without further warning. Later, when the user comes back to your application, your activity is given an onCreate call with that original bundle from which to restore its state. This will happen to all your activitys in what was your original stack.
Being able to restore your state from the bundle (which Android will save for you as your process goes away) is how Android maintain's the myth of multi-tasking. If you don't dump your activity's state out to a bundle each time onSaveInstanceState is called, your app will look like it's been restarted when the user may have just switched out for a second. This can be especially troubling when the system is resource constrained as the system would need to kill off processes more often in order to keep the device running quickly
Why the Application can be Bad
The Application does not actually get a chance to save any of its data if the process is shut down. It does have an onDestroy method but the docs will tell you that this actually never gets called by the system on an actual device. This means that, in the constrained case I mentioned above, any incidental information about what's going on within an Activity (if you've saved it in the Application) will be lost if the process is ended.
Developer's often miss this case (and it can be really annoying for users) because they're either running on a dev phone which never gets hit with using many applications at the same time. We're also never using the app for a while, then switching to another application and, after a while, switching back again.