Как изменить вид текста после нажатия на активные и неактивные кнопки в моей программе? - PullRequest
0 голосов
/ 01 июня 2018

У меня есть две кнопки с названиями «Активный» и «Деактивный» и TextView.когда я нажимаю на кнопку «Активно», он должен отправить SMS-сообщение, содержащее сообщение «CMDSAD_ON», на номер телефона и установить «Включить» для моего TextView, а при нажатии на кнопку «Деактивировать» он должен отправить «CMD_OFF» и установить «Отключить»к тому же TextView.

Но когда я запускаю его, он только устанавливает «отключить» текстовое представление и не будет меняться всякий раз, когда я нажимаю кнопки, и даже устанавливает его перед отправкой SMS.Я не знаю, как я могу решить свои проблемы.Спасибо

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

        //intent to filter for SS message received.
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");

       // Button2 is the id of "Active button" and Button4 is the id   of "Deactive button".

        Button button1 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(this);
        Button button2 = (Button) findViewById(R.id.button4);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.button2:

                String mymsg = "CMDSAD_ON";
                String thenumber = "916722";
                sendMsg (thenumber, mymsg);


            case R.id.button4:
                String msg = "CMDSAD_OFF";
                String phonenumber = "916722";
                sendNackMsg(phonenumber, msg);

            default:
            }}

и функция sendNackMsg похожа на sendMsg за исключением последней ссылки, которая изменяет текстовое представление на «отключить» (-> Textstatus.setText («отключить»);)

public void sendMsg (String thenumber, String mymsg){
        String SENT = "Message sent";
        String DELIVERED = "Message delivered";


        SmsManager smsManager = SmsManager.getDefault();

        Context curContext = this.getApplicationContext();

        PendingIntent sentPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("SENT"), 0);

        curContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sent.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
                                Toast.LENGTH_LONG).show();
                        break;
                }
            }
        }, new IntentFilter("SENT"));

        PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("DELIVERED"), 0);

        curContext.registerReceiver(
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "Delivered.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
                                        Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                }, new IntentFilter("DELIVERED"));

        PackageManager pm = this.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
                !pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
            Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
        } else{
            smsManager.sendTextMessage("9167227450", null, "CMDSAD_ON_1234", sentPending, deliveredPending);
        setContentView(R.layout.activity_main);
        TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
        Textstatus.setText("enable");}
    }


public void sendNackMsg(String phonenumber, String msg) {
        String SENT = "Message sent";
        String DELIVERED = "Message delivered";


        SmsManager smsManager = SmsManager.getDefault();

        Context curContext = this.getApplicationContext();

        PendingIntent sentPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("SENT"), 0);

        curContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sent.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
                                Toast.LENGTH_LONG).show();
                        break;
                }
            }
        }, new IntentFilter("SENT"));

        PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("DELIVERED"), 0);

        curContext.registerReceiver(
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "Delivered.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
                                        Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                }, new IntentFilter("DELIVERED"));

        PackageManager pm = this.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
                !pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
            Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
        } else{
            smsManager.sendTextMessage("09167227450", null, "CMDSAD_OFF_1234", sentPending, deliveredPending);
            setContentView(R.layout.activity_main);
            TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
            Textstatus.setText(disable);}
    }

Ответы [ 2 ]

0 голосов
/ 01 июня 2018

Вы не применили заявление break к своему onClick.Вот почему это всегда приводит к вашему последнему случаю и отключению вашего TextView.Проверьте это:

 @Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.button2:

            String mymsg = "CMDSAD_ON";
            String thenumber = "916722";
            sendMsg (thenumber, mymsg);
            break;

        case R.id.button4:
            String msg = "CMDSAD_OFF";
            String phonenumber = "916722";
            sendNackMsg(phonenumber, msg);
            break;
        default: 
            break;
        }
  }
0 голосов
/ 01 июня 2018

Здесь вы устанавливаете фиксированный текст для нажатия обеих кнопок

Используйте это условие для вашего buttonOnCLick и применяйте оператор break; после всех ваших нажатий кнопки.

Используйте то же самое, что и это условиенажмите обе кнопки и просто измените это

 String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

На свой button4 Нажмите

       String msg = "CMDSAD_OFF";
            String phonenumber = "916722";
            sendNackMsg(phonenumber, msg);

Замените код сообщения, как вы делали это раньше, в обоих условиях это для button2щелкните

    if(myTargetButton.getText().toString.equalsIgnoreCase("active")){

    myTargetButton.setText("Disable")
    String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

    }else if(myTargetButton.getText().toString.equalsIgnoreCase("Disable")){

    myTargetButton.setText("Enable")
    String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

    }



 TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
    Textstatus.setText("فعال");}

Измените его и используйте текст из вашего метода, например:

TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
        Textstatus.setText(mymsg);}

Надеюсь, он вам подходит.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...