The makeMainSelectorActivity()
approach is the right one, but we can try a direct approach as a fallback:
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
startActivity(
Intent.makeMainSelectorActivity(
Intent.ACTION_MAIN,
Intent.CATEGORY_APP_CALCULATOR
)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
} catch (t: Throwable) {
try {
startActivity(
Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_APP_CALCULATOR)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
} catch (t: Throwable) {
Toast.makeText(
this,
"Sorry, I cannot find a calculator",
Toast.LENGTH_LONG
).show()
}
}
}
}
The Toast
would be replaced by whatever you want as an error state if you cannot find a calculator app by either means. Here are the results on a variety of test devices:
Pixel 4/Android 11: launches the stock calculator app
Samsung Galaxy S8/Android 10: Toast
, because Samsung developers did not advertise their calculator app as being a calculator app, so third-party apps like yours have no way to identify it
Nokia 7.1/Android 10: launches the stock calculator app
LG V20/Android 8: launches the stock calculator app
Pixel 3XL/Android 12 Beta: launches the stock calculator app
Samsung Galaxy A50/Android 11: Toast
, probably for the same reason as the Galaxy S8
You are certainly welcome to try some Intent
objects for specific calculator apps, such as Samsung's, in hopes of improving your match rate. But, in the end:
- Manufacturers do not have to include a calculator app
- The current user might not have access to the calculator app (e.g., restricted profile)
- An app that is a calculator might not advertise itself as a calculator app via
CATEGORY_APP_CALCULATOR
, in which case there is no guaranteed way to find out that the app is a calculator app
So, you are going to need to settle for many, but not all, of your users being able to start the calculator app.