Android 如何检查哪个意图启动了活动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11529529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:55:51  来源:igfitidea点击:

how to check which Intent started the activity?

android

提问by Fawzinov

I have many activities. Each one of them has an intent which refers to the same activity. Is there a way to find out which intent started the activity?

我有很多活动。他们每个人都有一个意图,指的是同一个活动。有没有办法找出哪个意图开始了活动?

回答by ρяσ?ρ?я K

try as:

尝试如下:

Intent intent = new Intent();  
intent.setClass(A.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_A");  
A.this.startActivity(intent);

Intent intent = new Intent();  
intent.setClass(B.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_B");  
B.this.startActivity(intent);

Intent intent = new Intent();  
intent.setClass(C.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_C");  
C.this.startActivity(intent);

and in onCreate of main Activity:

并在主要活动的 onCreate 中:

//obtain  Intent Object send  from SenderActivity
 Intent intent = this.getIntent();

  /* Obtain String from Intent  */
        if(intent !=null)
        {
        String strdata = intent.getExtras().getString("Uniqid");
         if(strdata.equals("From_Activity_A"))
         {
         //Do Something here...
         }
         if(strdata.equals("From_Activity_B"))
         {
         //Do Something here...
         }
         if(strdata.equals("From_Activity_C"))
         {
         //Do Something here...
         }
         ........
        }
        else
        {
            //do something here
        }

use putExtrafor sending Unique key from Each Activity to identify from which Activity intent is Received

使用putExtra从每个活动发送的唯一键,以确定从哪个活动意图接收

回答by Sam

You didn't provide any context, so here's one general approach.

您没有提供任何上下文,因此这是一种通用方法。

Put an extra into each Intent type, like a unique int or String:

在每个 Intent 类型中添加一个额外的内容,例如唯一的 int 或 String:

intent.putExtra("Source", "from BroadcastReceiver");

and use:

并使用:

String source = getIntent().getStringExtra("Source");

回答by codeshark

I found a solution that doesn't involve passing data from one Activity to another.

我找到了一个不涉及将数据从一个 Activity 传递到另一个 Activity 的解决方案。

Use startActivityForResult in your calling activity to start the activity:

在您的调用活动中使用 startActivityForResult 来启动活动:

ActivityCompat.startActivityForResult(this, new Intent(this, MyActivity.class), 0, null);

In the callee Activity, you can use the following code to detect the calling activity.

在被调用者Activity中,可以使用以下代码来检测调用者Activity。

    if (getCallingActivity() != null) {
        Log.d(TAG, getCallingActivity().getClassName());
    }

Hope this helps. Cheers.

希望这可以帮助。干杯。