how to check which Intent started the activity?

后端 未结 3 1441
深忆病人
深忆病人 2021-02-13 02:11

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?

相关标签:
3条回答
  • 2021-02-13 02:39

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

    Use startActivityForResult in your calling activity to start the activity:

    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.

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

    Hope this helps. Cheers.

    0 讨论(0)
  • 2021-02-13 02:44

    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.putExtra("Source", "from BroadcastReceiver");
    

    and use:

    String source = getIntent().getStringExtra("Source");
    
    0 讨论(0)
  • 2021-02-13 02:46

    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:

    //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 putExtra for sending Unique key from Each Activity to identify from which Activity intent is Received

    0 讨论(0)
提交回复
热议问题