美文网首页Android
Use intent to start an activity

Use intent to start an activity

作者: JaedenKil | 来源:发表于2018-04-11 15:56 被阅读5次

    Basically we can start an activity with this:

    void startApp(Context ctx, String packageName, String activityName) throws ClassNotFoundException {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClassName(packageName, activityName);
            ctx.startActivity(intent);
    }
    
    private Context mContext = InstrumentationRegistry.getTargetContext();
    ...
    private String activityName02 = "com.google.android.finsky.activities.TvMainActivity";
    private String packageName02 = "com.android.vending";
    ...
    startApp(mContext, packageName02, activityName02);
    

    But meanwhile, when the activity is named with a ".", it will throw an exception.

    android:name
    The name of the class that implements the activity, a subclass of Activity. The attribute value should be a fully qualified class name (such as, "com.example.project.ExtracurricularActivity"). However, as a shorthand, if the first character of the name is a period (for example, ".ExtracurricularActivity"), it is appended to the package name specified in the <manifest>.

    So the following code will work:

    private String settingsPackageName = "com.android.tv.settings";
    private String activityName = settingsPackageName + ".accessories.AddAccessoryActivity";
    startApp(mContext, settingsPackageName, activityName);
    

    We need to add the package name before the ., and treat the whole as the activity name.

    相关文章

      网友评论

        本文标题:Use intent to start an activity

        本文链接:https://www.haomeiwen.com/subject/kxhzhftx.html