Need Suggestion to do a task when Android Boots-Up - android

I have written an activity A, when users press a button, it will do MyConfig.doSomething() where MyConfig is simple class with activity A passed to it.
public class A extends PreferenceActivity {
private MyConfig mMyConfig;
/* pseudo code, when button clicked, call */
mMyConfig.doSomething();
}
In mMyConfig, it accesses SharedPreferences for some configuration. Thus, I can do this to pass the activity to mMyConfig for calling getSharedPreferences().
mMyConfig = new MyConfig ( this );
Here comes my request:
I want to do something that MyConfig.doSomething() already does, but except when users click some button to invoke it, I want to invoke it when Android Boots-Up.
I can write another class to extend BroadcastReceiver and then starts activity A by calling startActivity(A.class), and then in A, do some tricks to make mMyConfig.doSomething() happen. It works but the Application will be shown on screen when Android Boots-Up.
I want to make mMyConfig.doSomething() happen implicitly without letting users be aware of it. I suppose two possible solutions but I don't know how to do it.
Solution A:
Write a class that extends BroadcastReceiver, start a service (instead of activity A) that reads the SharedPreferences of A and create MyConfig object to do doSomething(). However, I don't if this can work if activity itself is never launched and how could I do this (read SharedPreferences from a service)?
Solution B:
Write a class that extends BroadcastReceiver, start activity A without showing it, put it to activity stack by calling startActivity(A.class) in onReceive. Is this possible?

Instead of Activity, which are meant to be visible to the user, you can make your BoardcastReceiver to start a Service instead. It is meant to perform tasks in the background without disturbing the user. The official guide is a nice place to start with.
Edited:
To access the SharedPreference of your application, simply call this line inside your service:
SharedPreferences pref = PreferenceManager.getSharedPreferences();

Related

can I use activiy one time(register activity) and switch the main launcher to different activity?

can I use activiy one time(register activity) and switch the main launcher after using to different activity?
another question if I may,
If I create parameter x in one of the activities in my application, can I use this parameter in other activities?...If yes, how I can do that?
thanks :)
You cannot dynamically change the launcher activity once it has to be only 1 activity that is defined in the manifest file.
I would recommend having something like a landing or splash activity which checks a shared preference variable, to decide which activity to launch, for example either a login activity or another activity.
You should not access a variable in an activty from another activity, you should store these in data holding classes. however if you want to do it, for a good reason, simply make it static.
You cannot adjust the manifest after running your application. What you can do is have your default launcher activity write to SharedPreferences once it has been run once. Inside of that activity check to see if that preference has been set and if it has just finish that activity and launch your new activity, the user will not see anything if you do this in the onCreate of the launcher activity.
As for passing params between activities you should use intent extras. For example to pass a string use putExtra(String key, String value), and to get that parameter inside of the new activity use getStringExtra("Key").
For global variables accessable from different activities you can also extend Application class and then access it via getApplicationContext().
1. One time activity launch
You can't change the main launcher. It's a static information. What you could do is following:
// in the beginning of onCreate
// first launch could be loaded from shared preferences
// see 2. for more
if (!firstLaunch) {
// start another activity
finish();
return;
}
2. Use data in another activity
One way is to persist the data and load it somewhere else. You will find all information you need in the Data Storage article.
If your data is primitive you could try to pass it by intent to another activity. See Using integer from one class in another Android.
If it is complex you could try to implement an own Application class and use helper methods to access global data. See Android: Accessing resources without an Activity or Context reference.
Be careful with that, please read the Avoiding Memory Leaks article then.

Android: Access method in an activity from another activity

My launch activity starts up another activity whose launch is set to single instance. In this 2nd activity, I have a public method. I then start up a 3rd activity and that activity needs to access the public method in the 2nd activity. I don't want to use startActivity and pass it extras because I assume the onCreate will get called (or am I wrong?) and I need to avoid the 2nd activity from reinitializing itself.
When an activity is started using startActivity, is it possible to gain access to the underlying class instance itself and simply call the method?
I actually came up with a simple solution. As a matter of fact you can access the underlying class of an activity. First, you create a class that is used to hold a public static reference to activity 2. When activity 2 is created, in its onCreate method you store "this" in the static reference. Activity 2 implements an interface with the methods that you want available to any other activity or object. The static reference you hold would be of a data type of this interface. When another activity wants to call a method in this activity, it simply accesses the public static reference and calls the method. This is no hack but is intrinsic to how Java operates and is totally legitimate.
It is not a good idea.
As I can understand method from second activity is actually not connected to particular activity while you want to call it from another one. So carry the method out to other (non-activity) class (maybe static method) and use it from both activities.
It's not directly possible to gain access to activity object started using startActivity (without using some hacks). And frankly you shouldn't even trying to accomplish this.
One Activity component can cycle through several Activity java object while its alive. For example, when user rotates the screen, old object is discarded and new activity object is created. But this is still one Activity component.
From my experience, when you need to do things you described, there is something wrong with your architecture. You either should move part of activity's responsibilities to Service or to ContentProvider, or use Intents, etc. Its hard to recommend anything more specific without knowing more details.
No there is no way to pass a reference via startActivity() however you can use some sort of shared memory to keep reference to your Activity. This is probably a bad design. However passing an extra with your Intent will not cause onCreate, that is completely related to the lifecycle.

Android: Reusing an activity stored as local variable in another activity

I have two activities in my Android 2.1 application.
The first is the Main activity, with a view offering touch interaction.
The second is the Settings activity, offering settings to adjust parameters which are used within Main.
I currently have a Settings activity within my Main class, as a class instance. I read settings from this instance within Main.
public class Main extends Activity implements View.OnClickListener, View.OnTouchListener {
protected Settings settings;
}
public class Settings extends Activity implements ListAdapter {
}
I've discovered how to reuse my Settings activity if it has already been created, ensuring only one persistent instance:
// within Main.java :
Intent intent = new Intent(this,Settings.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // reuse existing Settings
this.startActivity(intent);
My issue is that I cannot discover how to tie this in with the local 'settings' member in Main.
Would someone be kind enough to give me a quick example of how I can start my local 'settings' instance as a reusable activity?
Many thanks
I currently have a Settings activity within my Main class, as a class instance.
Delete this immediately. One activity should not be holding onto another activity, as this results in memory leaks. I guarantee you that there are better solutions for whatever problem you think that you are solving this way.
My issue is that I cannot discover how to tie this in with the local 'settings' member in Main.
By deleting "the local 'settings' member in Main", this problem goes away.
Also, please use SharedPreferences and a PreferenceActivity for collecting "settings" wherever possible. For example, if the point behind "the local 'settings' member in Main" is to allow Main to access the settings, the right answer for that is for the settings to be stored in a SharedPreferences object and for Main to be using those SharedPreferences. Using a PreferenceActivity has the benefit of giving the user a look and feel that they expect when providing settings to an application.

Is there a way to make a function that's available to all Activities?

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.

Accessing Activity before it starts

I am using the InstrumentationTestCase class in order to unit test some things within an activity.
I need to be able to check the SharedPreferences's contents and edit them, before this activity is launched.
I cannot use the setUp method to create the Activity and access it's SharedPreferences object to edit it, and then close that activity before finishing the setUp method because it apparently is locking the tests processing.
I also cannot access the SharedPreferences after I have launched the activity inside the test because as soon as the Activity is launched, it will already change the SharedPreferences object and act according to it, before I had the chance to get it's reference.
I apparently cannot access the SharedPreferences before either, because I have no Activity object... and as soon as I do, it is already executing code and being launched...
So, my question is, is there any way to access the SharedPreferences (and any other Activity information) of this Activity before I have the Activity actually created through an Intent?
I cannot change it to an ActivityInstrumentationTestCase2 because my test uses a second activity in it's process, so I can't just change to this class and use it's setUp() method to access the SharedPreferences.
I found the best simpler way to do this through the instrumentation only, without having to edit the application's architecture or any of the access attributes.
I achieved it through this:
Instrumentation instrumentation = getInstrumentation();
instrumentation.getTargetContext().getSharedPreferences(..);
This way I can access the SharedPreferences before any Activity is launched by the instrumentation.
Thanks for all the help, hints and other alternatives anyway.
Well... To tell you frankly.. I am not able to visualize your scenario. But is checking for info in application is doable ?
Create a class which extends android.app.Application and specify class name in Manifests child application element.
Sample Code:
import android.app.Application;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
//try and access activity info here.
}
}
When your application is launched first class method to execture is onCreate of your application and has all the lifecyle events of that of any activity..
You must define extended application class in manifest by:
<application
android:name=".MyApplication"
android:label="#string/application_name">
I hope this ca give you some overview.
I haven't tried it, but if you set the mode to MODE_WORLD_READABLE and possibly MODE_WORLD_WRITEABLE instead of MODE_PRIVATE, I would think you could access the shared preferences from another application before the activity under test starts.
You could probably also use a different activity or service within the apk, or another apk that establishes a shared user ID and has the same certificate, to do the access without changing the access mode.

Categories

Resources