从另一个 class 调用 StartActivity(intent) 方法

Calling StartActivity(intent) method from another class

我有一个方法想从应用程序的多个位置调用。

public void openURL(String urlToOpen) {
    if (!urlToOpen.startsWith("https://") && !urlToOpen.startsWith("http://")){
        urlToOpen = "http://" + urlToOpen;
    }

    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlToOpen));

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getApplicationContext().startActivity(intent);
}

我可以从创建该方法的 class 中调用该方法,但我想从我应用程序的其他地方调用相同的方法。

此刻我得到一个 NullPointerException

04-23 13:08:08.958  22761-22761/com.myapplication. E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.myapplication, PID: 22761
    java.lang.NullPointerException
        at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
        at com.myapplication.MyMethodHandler.openURL(MyMethodHandler.java:213)
        at com.myapplication.HistoryListActivity.onClick(HistoryListActivity.java:111)

有什么建议吗?

我早该发现的简单答案。

我刚刚在方法中添加了一个Context参数,并在调用startActivity方法时使用了这个:

public void openURL(Context context, String urlToOpen) {
    if (!urlToOpen.startsWith("https://") && !urlToOpen.startsWith("http://")){
        urlToOpen = "http://" + urlToOpen;
    }

final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlToOpen));

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

}

然后从试图调用方法的 class 获取上下文:

Context context = this.getApplicationContext();

并在调用方法时传递了这个:

handler.openURL(context, urlToOpen);