I need to call the calculator from the click of a button, how can I do this? I'm having trouble, I'm a beginner on Android and I completely missed the implementation of this code.
I need to call the calculator from the click of a button, how can I do this? I'm having trouble, I'm a beginner on Android and I completely missed the implementation of this code.
In this post link I found the following code:
You will have to use Intent
, add these variables to your class MyActivity
:
private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";
private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";
Add this method to other methods:
public void launchCalculator()
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new Component Name(CALCULATOR_PACKAGE_NAME,
CALCULATOR_CLASS_NAME));
try {
this.start Activity(intent);
} catch (ActivityNotFoundException noSuchActivity) {
// handle exception where calculator intent filter is not registered
}
}
You can use launchCalculator
in the click event of your button, for example:
final Button button = (Button) findViewById(R.id.ID_DO_SEU_BOTAO);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
launchCalculator(); //Chama o Intent
}
});
It's been a while since I've been working with Java and Android, I may have missed something in the code, let me know if it fails.
The difficulty is that some manufacturers replace the pure Android standard calculator (package com.android.calculator2
) with their own applications, which are in a different package, so it is difficult to guess which package the calculator is.
But you can try to find the default calculator like this:
ArrayList<HashMap<String,Object>> items =new ArrayList<HashMap<String,Object>>();
final PackageManager pm = getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
for (PackageInfo pi : packs) {
if( pi.packageName.toString().toLowerCase().contains("calcul")){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("appName", pi.applicationInfo.loadLabel(pm));
map.put("packageName", pi.packageName);
items.add(map);
}
}
and then you can call the application by doing:
if(items.size()>=1){
String packageName = (String) items.get(0).get("packageName");
Intent i = pm.getLaunchIntentForPackage(packageName);
if (i != null) {
startActivity(i);
} else{
// Aplicativo não encontrado
}
}
Source: SOen