Cannot start new Intent by setClassName with different package in Android

前端 未结 9 1496
独厮守ぢ
独厮守ぢ 2020-12-06 11:30

I want to start a new Intent dynamically. Therefore setClassName seems the best choice.

First, I define 3 activity in Manifest



        
相关标签:
9条回答
  • 2020-12-06 11:44
    intent.setClassName(Act.this, Act1.class);
    
    0 讨论(0)
  • 2020-12-06 11:46

    The first param is the applicationId located in the build.gradle file

    The second param is full path to of the class with its package. for example: intentObj.setClassName("applicatioId", "com.youCompany.yourAppName.YourClassName")

    0 讨论(0)
  • 2020-12-06 11:46

    Use this code and you'll be fine.

    Intent intent = new Intent();
    String resourcePackageName = getResources().getResourcePackageName(R.string.some_defined_resource);
    intent.setClassName(getApplicationContext().getPackageName(),resourcePackageName + ".SubPackageName[/if any/].ClassName");
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-06 11:48

    Follow the syntax to write setClassName() method:

     setClassName( pkgName, className ) 
    
    0 讨论(0)
  • 2020-12-06 11:49

    You can use the following method to create the intent in the package context:

        Intent intent = new Intent(this, MyActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    

    This way you keep on generic code.

    HTH

    0 讨论(0)
  • 2020-12-06 11:53

    setClassName take a Package Context as first param setClassName(Context packageContext, String className):

    Intent intent = new Intent();
    if(index == 0) {
      intent.setClassName("com.example.pkg1", "com.example.pkg1.Act1");
    } else {
      intent.setClassName("com.example.pkg1", "com.example.pkg1.Act2");
      startActivity(intent);
    }
    

    and in

    <activity android:name="com.example.pkg2.Act" />
    <activity android:name="com.example.pkg1.Act1" />
    <activity android:name="com.example.pkg1.Act2" />
    

    or you try this :

    if(index == 0) {
      Intent intent = new Intent(Intent.ACTION_MAIN)
        .addCategory(intent.CATEGORY_LAUNCHER)
        .setClassName("com.example.pkg1", "com.example.pkg1.Act1")
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        .addFlags(Intent.FLAG_FROM_BACKGROUND)
        .setComponent(new ComponentName("com.example.pkg1", "com.example.pkg1.Act1"));
      getApplicationContext().startActivity(intent);
    } else {
      Intent intent  = new Intent(Intent.ACTION_MAIN)
        .addCategory(intent.CATEGORY_LAUNCHER)
        .setClassName("com.example.pkg1", "com.example.pkg1.Act2")
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        .addFlags(Intent.FLAG_FROM_BACKGROUND)
        .setComponent(new ComponentName("com.example.pkg1", "com.example.pkg1.Act2"));
      getApplicationContext().startActivity(intent);
    }
    
    0 讨论(0)
提交回复
热议问题