I see two ways to resolve this issue, depending on what you are ready to do:
- If
MyClass should be Activity
An Activity should be started correctly using startActivity() or any option. It must also be declared in your manifest. Thus, the following only works if all of your MyClass variants have the same signature.
I assume your startup code is in Activity . Right after loading classToLoad you can do the following:
final File tmpDir = getDir("dex", 0); final String libPath = Environment.getExternalStorageDirectory() + "/test.jar"; final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader()); try { final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shlublu.android.sandbox.MyClass");
Now change doSomething() so that it uses the base Context your new Activity instead of getApplicationContext() . Then call it from MyClass.onCreate() and see if it works:
public class MyClass extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); doSomething();
The rest is when to call doSomething() , why, etc. - depends on what you are ready to do.
- If
MyClass just needs to display Toast
There is no need to create another Activity in this case. doSomething() just needs to get the correct Context to display Toast .
Modify MyClass as follows:
public class MyClass { private void doSomething(Context ctx) { Toast.makeText(ctx, "MyClass: doSomething() called.", Toast.LENGTH_LONG).show(); Log.d(MyClass.class.getName(), "MyClass: doSomething() called."); } }
And change your startup code to pass this to doSomething() if it is running with Activity :
final File tmpDir = getDir("dex", 0); final String libPath = Environment.getExternalStorageDirectory() + "/test.jar"; final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader()); try { final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shlublu.android.sandbox.MyClass"); // CHANGED: LOADS THE METHOD doSomething(Context). EXECUTES IT WITH this AS AN ARGUMENT final Class[] args = new Class[1]; args[0] = Context.class; final Method doSomething = classToLoad.getMethod("doSomething", args); final Object myInstance = classToLoad.newInstance(); doSomething.invoke(myInstance, this); } catch (ClassNotFoundException e) { // handle that Exception properly here }