简体   繁体   中英

Is There any method by which I can call a method every time a new activity starts in an app?

I am using an external jar for some functionality in my Android project but I need to call the initialize function on every onStart() function. Is there a method, I can skip this step and it will automatically gets called every time a new activity start.

I am aware that some code injection techniques are available. Can some one please explain it in details or provide some source for it.

你可以试试这个:

protected void onCreate(Bundle savedInstanceState);

Make a class extend Activity class and put call to your library method in it's protected void onCreate(Bundle savedInstanceState); method.

Now make all your custom activities in which you need to call your library method on create extend above class rather than extending Activity directly.

In short use Inheritance!

onCreate(Bundle bundle) is the answer. You may also need to look for the onResume and onStart methods.

You might acheive this by creating a custom Activity class and overiding its onStart method. Then extend all your Activities from this custom Activity.

    public class CustomActivity extends Activity{
       @Override
       protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
           // call your method.
       }

    }

and then extend your activities from this custom Activity.

You do this as follows without modifying each activity.

Create a class which extends android.app.Application like

public class YourApplication extends Application {

    @Override
    public void onCreate() {
         // do whatever start-up processes you want to perform in this method
    }
}

Next, modify the application manifest files as follows

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="application.package"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
    ...
        android:name="application.package.YourApplication"
    ... >
    </application>
</manifest>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM