![](/img/trans.png)
[英]Why does my clickListener make my app crash only the second time i call it
[英]How to fix my app that crash instead of make a call?
我正在尝试制作一个在收到特定消息时开始通话的应用程序。 一切都很好,除了应用程序在应该开始呼叫时崩溃。
问题出在我使用startActivity()
的那一行。 我不知道为什么会崩溃。 有人能帮我吗?
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
@Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
//....
String cod = "message";
if(smsBody.compareTo(cod) == 0){
CallClass obj = new CallClass();
obj.call();
}
//....
private class CallClass extends AppCompatActivity {
public void call() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+107222222"));
startActivity(callIntent);
}
}
编辑:
我也试过下面的代码:
private class CallClass extends AppCompatActivity {
public void call() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+107222222"));
try{
startActivity(callIntent);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
}
但这并不能解决我的问题。 我检查并授予了应用程序开始通话所需的所有权限。 在调试模式下,我收到此消息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: romania.ovi.smsapp, PID: 9715
java.lang.RuntimeException: Unable to start receiver romania.ovi.smsapp.SmsBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3388)
....
W/System: A resource failed to call close.
确保你的 AndroidManifest.xml 中有这个
<uses-permission android:name="android.permission.CALL_PHONE" />
你的方法应该是这样的:
public void call(String message, Context context) {
if(message.compareTo("SpecificMessage")){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+40773733585"));
startActivity(callIntent);
}
}
问题是您试图将 Activity 用作另一个类。 根据经验,如果您正在调用 Activity 构造函数,那么您就做错了。 该类不应该是活动,或者您不应该调用构造函数。
在您的用例中,您最好在 BroadcastReceiver 本身中编写调用代码。
@Override
public void onReceive(Context context, Intent intent) {
...
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+107222222"));
context.startActivity(callIntent);
}
编辑:
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+107222222"));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.