Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何对不同的活动调用执行不同的功能?_Android_Android Activity_Mobile_Task - Fatal编程技术网

Android 如何对不同的活动调用执行不同的功能?

Android 如何对不同的活动调用执行不同的功能?,android,android-activity,mobile,task,Android,Android Activity,Mobile,Task,假设我有三节课:第一节、第二节和第三节 我实际上想做的是: 若我从第一个调用activity Second,那个么我希望执行一些task1,若我从第三个调用activity Second,那个么应该执行一些不同的task2 如何实现这一点?您可以传递一个带有一些标志的包,这样您就可以确定您来自第一个活动还是第三个活动。试试这个: public final static String EXTRA_PARAMETERS = "com.example....."; //some name

假设我有三节课:第一节、第二节和第三节

我实际上想做的是:

若我从第一个调用activity Second,那个么我希望执行一些task1,若我从第三个调用activity Second,那个么应该执行一些不同的task2


如何实现这一点?

您可以传递一个带有一些标志的包,这样您就可以确定您来自第一个活动还是第三个活动。试试这个:

    public final static String EXTRA_PARAMETERS = "com.example....."; //some name 


    //in first and third activities 
    Intent intent = new Intent(this, second.class);
    intent.putExtra(EXTRA_PARAMETERS, params); //params could be an array or something to identify from which activity you are calling second an int could be too.
    startActivity(intent);

    // in second activity
    Intent intent = getIntent();
    Bundle b = getIntent().getExtras();
    try{
       parameter = b.getParcelable(first.EXTRA_PARAMETERS); //you can do 2 of this and catch the one is not.
    }catch(Exception e){};

    try{
       parameter = b.getParcelable(third.EXTRA_PARAMETERS);
    }catch(Exception e){};

请初始化用作示例的所有变量。祝你好运如果您没有收到,请告诉我。

在启动
第二个
的意图中,放置一些
Bundle
数据,以标记此意图是来自
第一个
还是
第三个
。细节是

如果我这样做

// Constants.java
public static class Constants {
    public static String BUNDLE_KEY_FROM = "_BUNDLE_KEY_FROM";
}
在第一个
和第三个

Intent intent = new Intent(this, Second.class);
intent.putExtra(Constants.BUNDLE_KEY_FROM, "First"); // or "Third"
startActivity(intent);
然后在
第二个.onCreate()中


您可以将数据添加到第二次启动的意图中。在
onCreate
中,使用
getIntent()
读取数据和设备应执行的任务您的意思是,通过intent从第一个和第三个发送不同的文本,然后在第二个中使用if条件?选中此选项是,您可以更改附加到intent的数据或附加内容,尽管对于你想要做的事情,定制意图的行为可能是合适的。有没有办法做到这一点?if(val.equals(“First”){Second extends activity1}else(val.equals(“Third”){Second extends activity2}否。但是如果要使用不同的活动内容取决于
val
,为什么不使用?在
Second.onCreate()
中,您可以放置代码来选择和添加片段。
Bundle extras = getIntent().getExtras();
if (extras != null) {
    // get data via the key
    String val = extras.getString(Constants.BUNDLE_KEY_FROM);
    if (val.equals("First") ) {
        funcFirst();
    }else if(val.equals("Third") ){
        funcThird();
    }
}