![](/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.