在Android的动态启动活动?动态、Android

2023-09-12 04:33:33 作者:为你倾心

有没有办法来动态改变基于一个条件在Android中首发活动?我试图做(没有工作)为以下内容:

删除启动程序类别在我AndroidManifest.xml中定义的 创建一个自定义的应用程序类的应用程序使用 在重写我的应用程序类的onCreate方法来定义一些code这样的:

 如果(条件){
    startActivity(新意图(这一点,MenuActivity.class));
} 其他 {
    startActivity(新意图(这一点,LoginActivity.class));
}
 

解决方案

为什么不能有一个初步的活动,没有用户界面,检查条件的的onCreate ,然后启动下一个活动,然后调用完成()本身?我从来没有叫完成()从内部的onCreate()虽然,所以我不知道这是否会的工作。

修改 似乎很好地工作。下面是一些code,以使其更清晰。 初始活动

  @覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    意向意图;
    如果(条件){
       意图=新的意图(这一点,ClassA.class);
    } 其他 {
       意图=新的意图(这一点,ClassB.class);
    }
    startActivity(意向);
    完();
    //注意,我们从来没有所谓的setContentView()
}
 
android 动态 启动画面,用动画实现android app启动界面的渐变效果

其他活动

  @覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
}
 

Is there a way to dynamically change the starting activity in Android based upon a conditionally? What I attempted to do (that didn't work) was the following:

remove the LAUNCHER category as defined in my AndroidManifest.xml create a custom Application class that the app uses override the onCreate method of my Application class to define some code like the following:

.

if (condition) {
    startActivity(new Intent(this, MenuActivity.class));
} else {
    startActivity(new Intent(this, LoginActivity.class));
}

解决方案

Why not have an initial Activity with no UI that checks the condition in its onCreate, then launches the next Activity, then calls finish() on itself? I've never called finish() from within onCreate() though, so I'm not sure if this will work.

EDIT Seems to work fine. Here's some code to make it clearer. Initial Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent;
    if (condition) {
       intent = new Intent(this, ClassA.class);
    } else {
       intent = new Intent(this, ClassB.class);
    }
    startActivity(intent);
    finish();
    // note we never called setContentView()
}

Other Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}