我有 2 个 android 项目,A 和 B。我想从 A 项目的类(无 Activity)中调用 B 方法。例如,如果B项目是一个用jdk 1.6编写的纯Java项目,我不会有任何问题。但在这种情况下,它会崩溃。我在构建路径上添加了 B 项目,并在 order 和 export 中选择。
我不想使用 jar 库,因为我更喜欢根据我的要求调整 B 项目。我用这种方式来开发纯Java项目,它很有用。在此过程中,我创建了自己的库。
我把你的代码放在这里:
A类:
package com.example.a;
import com.example.b.ClassNoActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ClassNoActivity.showMessage(); // Here crashes
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
B类:
package com.example.b;
public class ClassNoActivity {
public static void showMessage() {
System.out.println("I'm a message.");
}
}
日志猫:
10-28 08:31:40.926: W/dalvikvm(3466): VFY: unable to resolve static method 4617: Lcom/example/b/ClassNoActivity;.showMessage ()V
10-28 08:31:41.156: W/dalvikvm(3466): threadid=1: thread exiting with uncaught exception (group=0x40db41f8)
10-28 08:31:41.166: E/AndroidRuntime(3466): FATAL EXCEPTION: main
10-28 08:31:41.166: E/AndroidRuntime(3466): java.lang.NoClassDefFoundError: com.example.b.ClassNoActivity
10-28 08:31:41.166: E/AndroidRuntime(3466): at com.example.a.MainActivity.onCreate(MainActivity.java:16)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.Activity.performCreate(Activity.java:4636)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1924)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1985)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.ActivityThread.access$600(ActivityThread.java:127)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.os.Handler.dispatchMessage(Handler.java:99)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.os.Looper.loop(Looper.java:137)
10-28 08:31:41.166: E/AndroidRuntime(3466): at android.app.ActivityThread.main(ActivityThread.java:4476)
10-28 08:31:41.166: E/AndroidRuntime(3466): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 08:31:41.166: E/AndroidRuntime(3466): at java.lang.reflect.Method.invoke(Method.java:511)
10-28 08:31:41.166: E/AndroidRuntime(3466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:816)
10-28 08:31:41.166: E/AndroidRuntime(3466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:583)
10-28 08:31:41.166: E/AndroidRuntime(3466): at dalvik.system.NativeStart.main(Native Method)