我正在尝试计算应用程序(子应用程序)加载,点击查询并填充屏幕所花费的时间。为此,我创建了另一个简单的应用程序(父级应用程序),只需按一下按钮即可。单击此按钮后,Child应用程序将启动一定数量的迭代。我可以从父应用程序调用子应用程序,但是父应用程序不等待子应用程序完成执行。
这是父应用程序中的 onClick 代码段:
public void onClick(View v) {
Intent launchIntent = this.getPackageManager().getLaunchIntentForPackage("com.example.android.packagename");
//null pointer check in case package name was not found.
if (launchIntent != null) {
try {
long launchStartTime = System.currentTimeMillis();
launchIntent.putExtra("LaunchStartTime", launchStartTime);
System.out.println("Launching child app");
/*Call child app 10 times. */
for (int i = 0; i <= 10; i++) {
startActivity(launchIntent);
/*Parent app doesn't waits for child app to finish its execution, and below statement is executed.*/
System.out.println("This will be printed and child app is launched only once.");
}
} catch (ActivityNotFoundException err) {
Toast t = Toast.makeText(getApplicationContext(),"App not found", Toast.LENGTH_SHORT);
t.show();
}
}
}
解决方案可能是使用多线程,但是我在该领域没有经验。任何人都可以提供一种方法,使父应用程序等待子应用程序完成其执行,并可能迭代所需的次数。
编辑:
现在,我试图在子线程上仅调用一次应用程序。我试图从主线程中产生一个子线程,并在子线程上调用子应用程序
但是我遇到了以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.app.ActivityThread $ ApplicationThread android.app.ActivityThread.getApplicationThread()'
这是新的 onClick 代码段:
public void onClick(View v) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
这是实现 runnable 接口的 MyRunnable 类。
public class MyRunnable extends AppCompatActivity implements Runnable {
@Override
public void run() {
Intent launchIntent = ApplicationContextProvider.getContext().getPackageManager().getLaunchIntentForPackage("com.example.android.packagename");
if (launchIntent != null) {
try {
startActivity(launchIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}