I'm trying to programatically call Home button with another button inside my project. App compiles fine, but when I tap the button that should call Home I receive following error:
Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
Here is my code (just essentials):
import android.app.Activity;
import android.content.Intent;
import android.content.Context;
public class ClassName extends ReactContextBaseJavaModule {
private Context context;
@ReactMethod
public void minApp() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
}
}
What am I doing wrong?
SOLUTION:
Due to the fact that my app uses react native, the code in bridged method in java file should look as below:
import android.content.Intent;
import android.content.Context;
public class ClassName extends ReactContextBaseJavaModule {
@ReactMethod
public void minApp() {
Context context = getReactApplicationContext();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
}
}
Using this we can assign Home button
function anywhere we want ;)
public void openLauncher(Context context) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
}
You can just open the launcher using this function.