Inside my Application class, I have a long-running function (e.g. downloading new data). Once the operation finishes, I want to inform several related activities to refresh their UI. What is the best way to achieve this in Android (the equivalent of postNotification in iOS)?
public class MyApplication extends Application{
public void onCreate() {
downloadDataInBackground(); // call operationDone when finished
}
private void operationDone(){
sendMessageToAllRelatedActivities();
}
}
You can use: Broadcast Receivers for this. Please see following link:
http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
I think you should use the Observer design pattern in order to notify that a certain status is changed
Observer
Related
I want to create an interface which will interact with an already running Service from the Activity in foreground.
viz, if there is a service called MyService running in background and I want to use the methods defined in the service from an activity called MyActivity then how will I do it.
There are several possibilities for an activity to communicate with a service and vice versa.
LocalBroadcast receiver that is provided by Android framework , v4 support library also provided.
AIDL for services in a different process
Handler and ResultReceiver or Messenger
To get details implementation visit following links :
http://www.vogella.com/tutorials/AndroidServices/article.html
http://developer.android.com/guide/components/services.html
You need to make your service bindable. or more specifically something like this LocalService taken from the android guide.
The above answers are pretty apt ....but if you are bent on interfaces then... below is how one can do using interfaces ...but a better and more preferred way is described here
Create a Interface with a function as below:
public interface OnChangeListener {
void onChange();
}
then in your service :
private OnChangeListener changeListener;
public void setChangeListener(OnChangeListener changeListener) {
this.changeListener = changeListener;
}
Some where in your service :
changeListener.onChange();
then from your Activity do this :
MyService.getInstance(this)
.setChangeListener(new OnChangeListener() {
#Override
public void onChange() {
// do something here
}
});
I am creating a android library, In that I want to find if the OnCreate of the main application is running? . I dont know whether oncreate fire any listener. Anybody knows will oncreate fires any listener. Any ideas? Thanks.
No this callback does not exist.
The way most libraries introduce this callback is by making a base type that they require another application to call back into. Like you could make your library do something like:
public class MyLibBaseApplication extends Application {
public void onCreate() {
super.onCreate();
// my callback stuff.
}
}
and then require all the users of your library either use or extend your Application object as the Application class in their manifest. This way sort of sucks for developers though, although there are a few libs that do this. It blocks you from using multiple libs with this same pattern (Super annoying).
Personally I think just asking for a callback from whoever is using the library is probably much better from a client and dev who would integrate a library.
Just a simple call or static function that would be like:
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
//register
YourLibrary.onCreateFired(this);
// or istantiate and register
YourLibraryCallback cb = new YourLibraryCallback(this);
cb.onCreateFired();
}
}
This way I think offers the most flexibility.
I have a one notification service which fires at every 5 seconds and get the data and parse it and then display it..
But this mechanism works only for the home screen of the app.
I want this to be done in every screen of the app.For that should i write the same code in every activity of the project ? It is very tedious job . I want to make it generalize ..
How to do that ?? any ideas??
you can make BasicActivity and have method in that Activity and call that method inside onCreate();
now extend every Activity in your project from your BasicActivity
If you are talking push notification service, this idea seems to problematic. tell us more what are you exactly trying to do.
you do something like this in some utility class
public static void showNotifction(Activity a)
{
//notify
}
and over this if you have any call back methods.. Then create an interface with those methods and implement them in all those Activities and you can do this..
public static void showNotifction(CommoInterface a)
{
if(a insatncof Activity){
//notify
a.callBack(); // callBack is a method in the interface..
}
}
I have a set of commands that I want my app to run when it's restarted, regardless of what activity it's on. I know I need to put an onRestart() into every one.
Since it's the same set of commands regardless of what activity it's on, is there a way I could have them all refer to a single function for that? It seems like that would be better then having to copy paste the commands into each onRestart() handler. It will be a lot less work if I need to change the set of commands too.
You have a couple of options, depending on the code.
You can put it in a helper class as a static function: public static void doWork() { .. } This should work, unless whatever you are doing depends on being in the activity. You can generally just pass it what it needs though, like the Context.
Or, you could extend Activity with your own class, MyActivity and place the work in that onResume. Then extend MyActivity for each of your real activities. They will now automatically do that work when you call super.onResume(). This works well as long as you really want to do the same thing in every activity, and don't use a lot of specialized activities like ListActivity.
Edit:
public class MyHelper {
public static void doWork() {
// do your work here
}
}
public class MyActivity extends Activity {
public void onResume() {
super.onResume();
MyHelper.doWork();
}
}
A search for "static method" will provide more details.
Derive all your activities from a single class (something like ActivityBase) that, in turn derives from system-provided Activity. Then implement onRestart() in ActivityBase.
Is it your application that is restarting from scratch? Or just your activities that are restarting/resuming?
The Application class has an onCreate() method, and you can extend Application in your app to override its behavior. Just remember to change the name of the application in AndroidManifest.xml so it picks up your custom Application class when starting. This code would run before any activities start up. But it won't run every time an activity is stopped and restarted. If that's what you need, this won't do it.
You could also implement a singleton class that contains an initialize() method, or restart() method. You simply call it from onRestart() in each activity you want it in. It sounds like this special code ought to be localized away from your activities so I don't think I'd recommend extending Activity to put the code there.
I am working on an Application that require some interaction between two activities, and I am not sure of what is the best way to achieve it:
One of the Activities is a "Logbook" (Just a ListView that displays a bunch of events).
The other Activity allows the user to create the events, that will be sent (and displayed in the Logbook).
How do I notify my Logbook Activity when a new Event is ready to be added?
Also, where should I add the event to the database? From the Logbook Activity, when I add it to the ListView, or from the NewEvents Activity, as soon as it's ready?
Thanks!
Ok, I found how to do it, using a BroadcastReceiver:
In my Logbook activity, I just set up a new custom receiver onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logbook);
registerReceiver(new EventReceiver(this), new IntentFilter("SEND_NEW_EVENT"));
Now, I can make the calls in my newEventActivity:
public void sendToLogbook(int eventId){
Intent i = new Intent("SEND_NEW_EVENT");
i.putExtra("newEvent", this.newEvents[eventId]);
sendBroadcast(i);
}
Of course, I had to create my CustomReceiver Class, and override the onReceive() method to do what I want:
public class EventReceiver extends BroadcastReceiver {
private ActivityLogbook activity;
public EventReceiver(ActivityLogbook activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.addToReport((Event)i.getParcelableExtra("newEvent"));
}
}
It works great so far, but if you do have comments/concerns about this, please tell me!
Thank you!
If I recall cporrectly the Notepad project which is included in the android sdk and is also part of the tutorials online is a good examaple which should satisfy your needs.
To borrow from MV-* (Model-View-something or other) patterns, separate your idea of the Model (in this case, your Event objects) and what is displaying them (the View, or in your case an Activity) and it'll become more clear.
If you have your events somewhere global where all activities can interact with them, then you can work with the model and display the model from wherever and however you choose.
One simple suggestion is have a class (EventController or something like that) that allows you to interact with the Events collection, and make it available through a derived Application class. I can explain further if that doesn't make sense. I have a pattern I use in my Android apps whereby all Activity classes have access to a custom global Application instance, so my model is a model and can be accessed by whatever Activities I want to have access.
This is merely one approach, and as always, there are many that may suit your needs.
One possibility would be:
The ListActivity gets all the data each time it is resumed and updates the ListView accordingly
The NewEventActivity does all the job of storing the Event and simply finishes
You can improve it a bit more:
The ListActivity gets all the data when it starts
The ListActivity starts the NewEventActivity expecting a OK/CANCELLED result
The NewEventActivity does all the job of storing the Event and returns a result saying OK or CANCELLED
Depending on the result it gets from the NewEventActivity, ListActivity reloads its data or not