I want to go to the home screen programmatically in Android when the user clicks on button. How can this be done?
I want to go to the home screen programmatically in Android when the user clicks on button. How can this be done?
Janusz's answer is great.
The only thing I want to add, which is a little too long for a comment, is that you can go to the home screen without having a reference to the current activity.
Janusz's code needs to be called from an Activity or Fragment due to startActivity(),
To get around this, you can store a static reference to your apps Context in your application file:
public class YourApplication extends Application
{
private static Context mAppContext;
public void onCreate()
{
super.onCreate();
...
YourApplication.mAppContext = getApplicationContext();
}
public static Context getContext()
{
return mAppContext;
}
}
Now you can send the user to the device home screen from any class in your app, not just Activities, Fragments, or other Classes with a reference to the current Activity (you can decide whether this is a good or bad thing):
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
YourApplication.getContext().startActivity(startMain);
startActivity((new Intent(Intent.ACTION_MAIN)).addCategory(Intent.CATEGORY_HOME).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));