首页 > 代码库 > Android - Error:Calling startActivity() from outside of an activity context

Android - Error:Calling startActivity() from outside of an activity context

Error:Calling startActivity() from outside of an activity context


本文地址: http://blog.csdn.net/caroline_wendy


Android错误:Calling startActivity() from outside of an activity context requires the FLAG_ACTIVITY_NEW_TASK
在一个Activity外部调用本地的startActivity(),需要在Intent内设置FlagFLAG_ACTIVITY_NEW_TASK

原因:
startActivity()错误,在另一个类的方法中,跳转至其他界面;
启动默认的系统设置(setting)界面,需要传递Intent:
Intent i = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);

但是,如果在另一个类中启动,则需要Intent添加Flag参数,FLAG_ACTIVITY_NEW_TASK
正确写法如下:
public static void gotoLocServiceSettings(Context context) {
        final Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

不会报错

Android - Error:Calling startActivity() from outside of an activity context