0

我有一个 android 应用程序,它发送多条消息并调用点击事件。问题是

我有两个点击事件。在第二次点击事件中,代码运行完美,但在第一次点击事件中,相同的代码不起作用(即它不发送任何消息)。这可能看起来很愚蠢,但我无法找出错误。请告诉我如何解决这个问题。

如果需要任何其他信息,请通知我。

我的代码是:

     public class MainActivity extends AppCompatActivity {


            ArrayList<String> ar = new ArrayList<String>();


            public static final String MyPREFERENCES1 = "MyPrefs1" ;
            public static final String C11 = "contact11";
            public static final String C12 = "contact12";
            public static final String C13 = "contact13";
            public static final String C14 = "contact14";
            public static final String MSG11 = "msg11";
            public static final String MyPREFERENCES2 = "MyPrefs2" ;
            public static final String C21 = "contact21";
            public static final String C22 = "contact22";
            public static final String C23 = "contact23";
            public static final String C24 = "contact24";
            public static final String MSG22 = "msg22";


            RelativeLayout b1,b2,b3,b4,b5;
            Uri smsToUri;
        //    String c11,c12,c13,c14,msg11;
            String c21,c22,c23,c24,msg22;



            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);



                 b1 = (RelativeLayout) findViewById(R.id.LinearLayout1);
                 b2 = (RelativeLayout) findViewById(R.id.LinearLayout2);



                SharedPreferences prfs = getSharedPreferences(MyPREFERENCES1, Context.MODE_APPEND);
                 c11 = prfs.getString(C11, "");
                 c12 = prfs.getString(C12, "");
                 c13 = prfs.getString(C13, "");
                 c14 = prfs.getString(C14, "");
                 msg11 = prfs.getString(MSG11, "");

    First click event

                assert b1 != null;
                b1.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        File f = new File(
                                "/data/data/com.example.neo.dial_test/shared_prefs/MyPrefs1.xml");


                        if (f.exists()) {
                            if (c11.toString().equals(C11)||c11.toString().equals("")||c12.toString().equals(C11)||c12.toString().equals("")||c13.toString().equals(C11)||c13.toString().equals("")||c14.toString().equals(C11)||c14.toString().equals("")){

                                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                    return;
                                }
                                Intent intent3 = new Intent(Intent.ACTION_CALL);
                                intent3.setData(Uri.parse("tel:11223321"));
                                intent3.putExtra("com.android.phone.extra.slot", 0);
                                startActivity(intent3);
                                Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                for (int i = 0; i < ar.size(); i++)
                                {
                                    String message = msg11.toString();
                                    String tempMobileNumber = ar.get(i).toString();
                                    multipleSMS(tempMobileNumber, message);
                                }
                            }

                            else {
                                Intent intent3 = new Intent(Intent.ACTION_CALL);
                                intent3.setData(Uri.parse("tel:9506171242"));
                                intent3.putExtra("com.android.phone.extra.slot", 0);
                                startActivity(intent3);
                                Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                for (int i = 0; i < ar.size(); i++)
                                {
                                    String message = msg11.toString();
                                    String tempMobileNumber = ar.get(i).toString();
                                    multipleSMS(tempMobileNumber, message);
                                }
                            }


                        }
                        else{

                            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                return;
                            }
                            Intent intent3 = new Intent(Intent.ACTION_CALL);
                            intent3.setData(Uri.parse("tel:9506171243"));
                            intent3.putExtra("com.android.phone.extra.slot", 0);
                            startActivity(intent3);
                            Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                        }
                    }
                });

                SharedPreferences prfs2 = getSharedPreferences(MyPREFERENCES2, Context.MODE_APPEND);
                c21 = prfs2.getString(C21, "");
                c22 = prfs2.getString(C22, "");
                c23 = prfs2.getString(C23, "");
                c24 = prfs2.getString(C24, "");
                msg22 = prfs2.getString(MSG22, "");


                ar.add(c21);
                ar.add(c22);
                ar.add(c23);
                ar.add(c24);
        //


Second click event       
                assert b2 != null;
                b2.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        File f = new File(
                                "/data/data/com.example.neo.dial_test/shared_prefs/MyPrefs2.xml");


                        if (f.exists()) {
                                if (c21.toString().equals(C11)||c21.toString().equals("")||c22.toString().equals(C11)||c22.toString().equals("")||c23.toString().equals(C11)||c23.toString().equals("")||c24.toString().equals(C11)||c24.toString().equals("")){

                                   if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                       return;
                                  }
                                    Intent intent3 = new Intent(Intent.ACTION_CALL);
                                    intent3.setData(Uri.parse("tel:9506171244"));
                                    intent3.putExtra("com.android.phone.extra.slot", 0);
                                    startActivity(intent3);
                                    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                    for (int i = 0; i < ar.size(); i++)
                                    {
                                        String message = msg22.toString();
                                        String tempMobileNumber = ar.get(i).toString();
                                        multipleSMS(tempMobileNumber, message);
                                    }
                                }

                            else {
                                    Intent intent3 = new Intent(Intent.ACTION_CALL);
                                    intent3.setData(Uri.parse("tel:9506171244"));
                                    intent3.putExtra("com.android.phone.extra.slot", 0);
                                    startActivity(intent3);
                                    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                    for (int i = 0; i < ar.size(); i++)
                                    {
                                        String message = msg22.toString();
                                        String tempMobileNumber = ar.get(i).toString();
                                        multipleSMS(tempMobileNumber, message);
                                    }
                                }


                        }
                      else{

                            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                return;
                            }
                            Intent intent3 = new Intent(Intent.ACTION_CALL);
                            intent3.setData(Uri.parse("tel:9506171244"));
                            intent3.putExtra("com.android.phone.extra.slot", 0);
                            startActivity(intent3);
                            Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                        }

                    } } );




            }


            private void multipleSMS(String phoneNumber, String message) {
                String SENT = "SMS_SENT";
                String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                        SENT), 0);

                PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                        new Intent(DELIVERED), 0);

                // ---when the SMS has been sent---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                ContentValues values = new ContentValues();
                                for (int i = 0; i < ar.size() - 1; i++) {
                                    values.put("address", ar.get(i).toString());
                                    // txtPhoneNo.getText().toString());
                                    values.put("body", ar.toString());
                                }
                                getContentResolver().insert(
                                        Uri.parse("content://sms/sent"), values);
                                Toast.makeText(getBaseContext(), "SMS sent",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                Toast.makeText(getBaseContext(), "Generic failure",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                Toast.makeText(getBaseContext(), "No service",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:
                                Toast.makeText(getBaseContext(), "Null PDU",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                Toast.makeText(getBaseContext(), "Radio off",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, new IntentFilter(SENT));

                // ---when the SMS has been delivered---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "SMS delivered",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "SMS not delivered",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, new IntentFilter(DELIVERED));

                SmsManager sms = SmsManager.getDefault();
                try{
                sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
            }catch (IllegalArgumentException ex){
                    Toast.makeText(getBaseContext(), "exception",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onBackPressed() {
                // mIsBackButtonPressed = true;
                // super.onBackPressed();
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle("Exit Application?");
                alertDialogBuilder
                        .setMessage("Click yes to exit!")
                        .setCancelable(true)
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // Write your code here to execute after dialog

                                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                                        startMain.addCategory(Intent.CATEGORY_HOME);
                                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(startMain);
                                        finish();
                                        MainActivity.isQuit = true;

        //                                Toast.makeText(getApplicationContext(), "ThanK You",
        //                                        Toast.LENGTH_LONG).show();
                                    }
                                })

                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                dialog.cancel();

                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
                return;
            }
            public static boolean isQuit = false;
        }

单击第二个按钮时出现错误日志

E/ActivityThread: Activity com.example.neo.dial_test.MainActivity has leaked IntentReceiver com.example.neo.dial_test.MainActivity$7@798546 that was originally registered here. Are you missing a call to unregisterReceiver()?
                  android.app.IntentReceiverLeaked: Activity com.example.neo.dial_test.MainActivity has leaked IntentReceiver com.example.neo.dial_test.MainActivity$7@798546 that was originally registered here. Are you missing a call to unregisterReceiver()?
                      at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:898)
                      at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:699)
                      at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1653)
                      at android.app.ContextImpl.registerReceiver(ContextImpl.java:1633)
                      at android.app.ContextImpl.registerReceiver(ContextImpl.java:1627)
                      at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
                      at com.example.neo.dial_test.MainActivity.multipleSMS(MainActivity.java:595)
                      at com.example.neo.dial_test.MainActivity.access$000(MainActivity.java:32)
                      at com.example.neo.dial_test.MainActivity$1.onClick(MainActivity.java:139)
                      at android.view.View.performClick(View.java:4757)
                      at android.view.View$PerformClick.run(View.java:19757)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

当我使用此代码处理上述错误时(您是否错过了对 unregisterReceiver() 的调用?)使用此代码:

private BroadcastReceiver sendBroadcastReceiver;
private BroadcastReceiver deliveryBroadcastReceiver;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    sendBroadcastReceiver = new BroadcastReceiver()
    {

        public void onReceive(Context arg0, Intent arg1)
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    deliveryBroadcastReceiver = new BroadcastReceiver()
    {
        public void onReceive(Context arg0, Intent arg1)
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));

public void sendSMS(String phoneNumber, String message)
{
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}

@Override
protected void onStop()
{
    unregisterReceiver(sendBroadcastReceiver);
    unregisterReceiver(deliveryBroadcastReceiver);
    super.onStop();
}
}

错误日志 更改代码后,将 multipleSMS 函数替换为新代码的 sendSMS 函数。

FATAL EXCEPTION: main
                  Process: com.example.neo.dial_test, PID: 20531
                  java.lang.IllegalArgumentException: Invalid destinationAddress
                      at android.telephony.SmsManager.sendTextMessage(SmsManager.java:243)
                      at com.example.neo.dial_test.MainActivity.sendSMS(MainActivity.java:611)
                      at com.example.neo.dial_test.MainActivity$3.onClick(MainActivity.java:185)
                      at android.view.View.performClick(View.java:4757)
                      at android.view.View$PerformClick.run(View.java:19757)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
4

0 回答 0