Android - 应用程序启动测试

时间:2015-01-05 05:31:30

标签: android android-intent nullpointerexception performance-testing

我正在创建一个应用程序,它将启动各种Android应用程序(即:联系人,日历,电子邮件...)并记录其启动时间。

为此,我有以下代码。



public class LaunchPerformanceBase extends InstrumentationTestCase {

public static final String LOG_TAG = "Launch Perf";

public Bundle mResults;
public Intent mIntent;

public LaunchPerformanceBase(String pkg_name, String class_name) {
    mResults = new Bundle();
    try {
        mIntent = new Intent(Intent.ACTION_MAIN);
        mIntent.setClassName("com.android.contacts.activities", "com.android.contacts.activities.PeopleActivity");
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } catch (NullPointerException e) {
        Log.d(LOG_TAG, "NULL POINTER EXCEPTION setClassName()");
        e.printStackTrace();
    }

}

/**
 * Launches intent, and waits for idle before returning.
 *
 */
public void LaunchApp() {
    try {
        Activity act = getInstrumentation().startActivitySync(mIntent); <-- LINE NUMBER 69
        getInstrumentation().waitForIdleSync();
        act.finish();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}
}
&#13;
&#13;
&#13;

从主应用程序中,我正在执行以下操作。

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                LaunchPerformanceBase LaunchData = new LaunchPerformanceBase("com.google.android.contacts", "com.android.contacts.activities.PeopleActivity");
                LaunchData.LaunchApp(); <--LINE NUMBER 38
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();
}

我在startActivitySync()调用时遇到NullPointerException。 01-05 08:55:59.430 4653-4692 / perftest.com.applicationlaunchtime W / System.err:java.lang.NullPointerException:尝试调用虚方法&#39; android.app.Activity android.app.Instrumentation.startActivitySync (android.content.Intent)&#39;在null对象引用上 01-05 08:55:59.430 4653-4692 / perftest.com.applicationlaunchtime W / System.err:at perftest.com.applicationlaunchtime.LaunchPerformanceBase.LaunchApp(LaunchPerformanceBase.java:69) 01-05 08:55:59.430 4653-4692 / perftest.com.applicationlaunchtime W / System.err:at perftest.com.applicationlaunchtime.MainActivity $ 1.run(MainActivity.java:38)

我是Android应用开发的新手,所以对此非常感谢。

1 个答案:

答案 0 :(得分:0)

您将获得空指针异常,因为此代码

public Intent mIntent;

此变量mIntent的范围贯穿LaunchPerformanceBase类。

在构造函数public LaunchPerformanceBase(String pkg_name, String class_name)中,您使用与上面相同的名称初始化了intent

Intent mIntent = new Intent(Intent.ACTION_MAIN);

当您在startActivitySync(mIntent);中致电LaunchApp()时,它指的是上面声明的public Intent mIntent;变量未初始化。这就是你得到Null指针异常的原因。

所以改变这行代码,

Intent mIntent = new Intent(Intent.ACTION_MAIN);

mIntent = new Intent(Intent.ACTION_MAIN);