Is there a sendToActivity() method? - android-activity

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

Related

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

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.

Is using registerReceiver on the application class cosidered a good, known practice?

Background
On Android, there are 2 possible ways to listen to system events via BroadcastReceivers :
statically, via the manifest
programmatically, via the code.
Since some projects contain a lot of activities, services, and "manager"-classes , it could be useful to have a single BroadcastReceiver that will notify all of its listeners on the app about what has happened, instead of having multiple BroadcastReceivers being used (and their code handling).
An example of such a BroadcastReceiver, is the one that listens to the connectivity changes:
#Override
public void onCreate() {
super.onCreate();
...
registerReceiver(new ConnectivityChangedBroadcastReceiver(), new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
...
}
The question
The purpose is to listen to the events while the app is "alive" (by services and/or activities) .
Using the manifest would miss this purpose, as it will wake the app each time the event occurs, even if the app doesn't need it.
Thing is, unregistering doesn't occur, and maybe it causes the OS treat the app in a different way because of it.
Does having a call to "registerReceiver" on the class that extends from Application is a good known practice?
Does it have any side effects and things to know about when using it?
Is there any alternative to this?
I just want to be sure it's considered safe to use.
we can't really know what is good or better for you.
I advise you to learn more about the difference between the registration ways of the receiver:
1/ in the manifest :
the handler of the receiver will be triggered each time that the correspondent event comes. Example: the messenger of facebook is lunched every time that you have internet connection to show you your notifications... or other applications are lunched when you connect to propose updates ...
in other words, the receiver is always registered.
2/ in a service or an activity or an application :
the receiver will be unregistered when the context of where it is registered is killed.
in other words, it depends totally of the context where it is registred , and you are obliged to unregister it somewhere in the code. exemple : one activity is waiting that a service ( which is doing something in the background) sends an alert to update something , then you can register the receiver in your onResume() and unregester it in your onPause().
Conclusion : It depends only in the life-cycle requirement of the receiver.
see also Broadcast Receiver Register in Manifest vs. Activity
Main difference between Manifest and Programmatic registering of BroadcastReceiver

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.

Play 2.0 - Push current state of execution to page

So I currently have an application independent of Play which may take a long time in its execution.
I want to put a UI on top of it using Play where the application may be invoked and to display some of the details of the execution inside of the application to the user. I would like the page to be updated automatically as the execution proceeds e.g. if a variable in the application increments this would be reflected on the page.
I'm not sure where to begin with this - do I need to split the application up into models + controllers ? Or do I just need to have code in a controller to instantiate the classes I have already coded and call the methods I need ?
What about constantly showing the execution state on the page?
Any resources I should know about/read ? Code examples?
Thanks
You may have already done so, but a good starting point is to create a skeleton Play application using the play new command, while referring the creating a new application section. You will have "views" (HTML template pages) and one controller (in Application.scala). You could add more controllers, but as you will have just a single page that should suffice.
You can add jars from your app (if it's a JVM app) to the lib directory of your Play application. From this: "Or do I just need to have code in a controller to instantiate the classes I have already coded and call the methods I need?" it sounds like you would be happy to have your app run in the process of the Jetty + Play server. Check out the Global object for starting your app at process startup.
Check out the section on comet sockets for sending updates from the Play app to the browser. You'll need a bit of Javascript in the web page.
Do you want to have this application running outside of play, perhaps on another server? Can you modify the application, or is this 3rd party software?
If so, you have to have some way to send data back and forth between your play front end and your application. You can either have your application expose a websocket, and then your play front end and your application can push data back and forth to each other. You can then have your client page have a websocket open to you play front end, and then play can push the updates to the client. If your application can't support a websocket, you could also expose some URLs on your front end for the application to POST to. You can then use some sort of message bus or database mechanism (RabbitMQ, redis, Mongo capped collection, or even just a shared Queue object) so that the front end websocket can get those updates and send them to the client.

When we use delegate and Call back in iOS?

I'm very new on iOS application development so please explain me about delegate and call back. When we use use call back and delegate?
Call backs are used to allow an API or service to provide information to your code when certain events occur (e.g. when a task has completed). This is useful in asynchronous programming, e.g. when you want your current thread to get on with something else, or to allow the user to continue using the UI. (i.e. a call back is a function or lambda you have written, which is passed as a parameter to another method)
A delegate is the 'signature' (the 'type definition' of a method, including parameters) that a method (such as a call back) must provide in order for it to be useable as callback or event handler.
Edit Just to be complete, Delegation is also a design pattern, whereby the responsibility of control or action is delegated from one object to another.
Big piece about delegates here on the dev centre:
http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html
There is a tutorial app using callback/delegate
http://brandontreb.com/objective-c-programming-tutorial-creating-a-twitter-client-part-1/