Android: Open the Calculator from Android using Intent

If you make an application and you need to open the calculator that comes with Android you can use the code bellow, but be careful because some Android phones might not have the Calculator installed or the name of the package and class might differ.

1. When you make the new project call your main activity Calculator like in our example for simplicity.
2. After you created the new project, go to the res – layout – main.xml and make a button with the id showCalculatorButton

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/showCalculatorButton"
            android:text="Show Calculator"/>

</LinearLayout>

3. And now go to Calculator activity and put the following code:

public class Calculator extends Activity {

    public static final String CALCULATOR_PACKAGE ="com.android.calculator2";
    public static final String CALCULATOR_CLASS ="com.android.calculator2.Calculator";


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        showCalculator = (Button) findViewById(R.id.showCalculatorButton);

        showCalculator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();

                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.setComponent(new ComponentName(
                CALCULATOR_PACKAGE,
                CALCULATOR_CLASS));

                Calculator.this.startActivity(intent);


            }
        });      
}

keyboard_arrow_up
sponsored
Exit mobile version