在 Intent 之前检查 SMS 和 DIal 支持

Check SMS and DIal support before Intent

我有此代码可通过 Intent 发送短信并拨打号码:

 public void Call(String s) {//Appeler
    String url = "tel:" + s;
    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
    startActivity(intent);
}
public void Sms(String s){
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", s, null)));
}

在我的 phone 中看起来不错,没有崩溃,但在我的不支持短信和通话的平板电脑(没有 sim 卡和短信和拨号应用程序)中,应用程序在调用这些时崩溃方法,那么如何处理该异常?

应该可行

PackageManager pm = this.getPackageManager();

 if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
     System.out.println("Supported");
 } else {
     System.out.println("nope");
 }

你可以这样处理:

public void Sms(String s){
    try {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", s, null)));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(getActivity(), "No app for this", Toast.LENGTH_LONG).show();
    }
}

您必须始终检查 Activity 是否可以处理您的 Intent

假设 Skype 安装在可以处理您的 呼叫 意图然后启动意图的平板电脑上

PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(intent,
        PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0; 
if(isIntentSafe)
{
 // call Call(546) or Sms(1235)
}else{
// No activity is present  to handle  your intent
}

同时检查这个 link