Use of Context to start another Activity

前端 未结 3 930
無奈伤痛
無奈伤痛 2020-11-30 11:36

To start an Activity you need an Intent, like:

Intent i = new Intent(context, class)

So to fill in the context parameter, a couple of optio

相关标签:
3条回答
  • 2020-11-30 11:46

    You do it like this....

    Intent intent = new Intent();
    intent.setClass(MainActivity.this, SecondActivity.class);
    startActivity(intent);
    
    0 讨论(0)
  • 2020-11-30 11:48

    They are different for sure. These are different contexts, and should be used with the least possible scope(context).

    For example if we can use Activity's Context instead of ApplicationContext, one should use the activity context, same applies to application context, and base context.

    0 讨论(0)
  • 2020-11-30 11:49

    Yes its different for different cases,

    It depends on the scope. Suppose if you are creating a method in a global class that extends Application to create a Toast that is used in every class of your Application you can use getApplicationContext() to create it.

    If you want to create a view that is restricted to that particular Activity you can use Activity.this

    Also if you want to create an AlertDialog in some inner class say AsyncTask, then you have to use Activity.this, because the AlertDialog is to be linked to Activity itself.

    Also don't use getBaseContext() just use the Context that you are having. For getting further information for the same you can see this Answer.

    So, the answer to the real question is better to use Activity.this to start a new Activity.

    Intent intent = new Intent(Current_Activity.this, Calling.class);
    startActivity(intent);
    
    0 讨论(0)
提交回复
热议问题