Приложение Android SMS неожиданно вызывает новый макет сообщения по умолчанию из приложения обмена сообщениями при нажатии кнопки

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

Когда я нажимаю кнопку «Отправить» в своем макете, он отправляет SMS и запускает тост, уведомляющий меня об отправленном SMS. Это работало отлично, пока я не попытался добавить атрибут onClick в XML, что привело к намерению начать новое действие... Вот когда это начало происходить:

Вместо того, чтобы запускать новое действие, которое я создал, оно отправило меня в макет / действие «Новое сообщение» приложения «Обмен сообщениями» по умолчанию, включенного в телефон. Я этого не понял, поэтому убрал (если я не пропустил что-то снова и снова) все, что я изменил с тех пор, как оно работало.

ПОКА: он все еще отправляет меня в это новое сообщение, когда я нажимаю эту кнопку...

Может кто-нибудь сказать мне, где в моем коде я говорю приложению начать это действие? Благодарю вас!

TextActivity.java

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TextActivity extends Activity {

Button buttonSend;
EditText textPhoneNo;
EditText textSMS;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.text_field);

    buttonSend = (Button) findViewById(R.id.bSendText);
    textPhoneNo = (EditText) findViewById(R.id.etPhoneNumber);
    textSMS = (EditText) findViewById(R.id.etTypeMessage);

    buttonSend.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            String phoneNo = textPhoneNo.getText().toString();
            String sms = textSMS.getText().toString();

            Intent sendIntent = new Intent(Intent.ACTION_VIEW);
            sendIntent.putExtra("SMS Body", sms);
            sendIntent.setType("vnd.android-dir/mms-sms");
            startActivity(sendIntent);

            try {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, sms, null, null);
                Toast.makeText(getApplicationContext(), "SMS Sent!",
                        Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "SMS failed, please try again later!",
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    });
}

// STARTING The Contact Selection Process
private static final int CONTACT_PICKER_RESULT = 1001;

// References the Select Contact Button with onClick="clickHandle"
public void clickHandle(View view) {
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
            Contacts.CONTENT_URI);
    startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}

// Interpreting the results from the Contact_picker
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
        case CONTACT_PICKER_RESULT:
            Cursor cursor = null;
            String phone = "";
            String name = "";
            try {
                Uri result = data.getData();

                // get the contact id from the Uri
                String id = result.getLastPathSegment();

                // query for everything phone
                cursor = getContentResolver().query(Phone.CONTENT_URI,
                        null, Phone.CONTACT_ID + "=?", new String[] { id },
                        null);

                int phoneIdx = cursor.getColumnIndex(Phone.DATA);
                int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);

                // let's just get the first phone
                if (cursor.moveToFirst()) {
                    phone = cursor.getString(phoneIdx);
                    name = cursor.getString(nameIdx);

                } else {

                }
            } catch (Exception e) {

            } finally {
                if (cursor != null) {
                    cursor.close();
                }
                EditText phoneEntry = (EditText) findViewById(R.id.etPhoneNumber);
                phoneEntry.setText(phone);

                TextView nameEntry = (TextView) findViewById(R.id.tvContactSelected);
                nameEntry.setText(name);

                if (phone.length() == 0) {
                    Toast.makeText(this, "No phone found for contact.",
                            Toast.LENGTH_LONG).show();
                }
            }
            break;
        }

    } else {

    }
}
}

Мой XML, text_field.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/burntorange" >

    <Button
        android:id="@+id/bSelectContact"
        android:layout_width="50dp"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:background="@color/gray"
        android:inputType="phone"
        android:onClick="clickHandle"
        android:text="+"
        android:textColor="@color/white"
        android:textSize="35dp" />

    <TextView
        android:id="@+id/tvContactSelected"
        android:layout_width="290dp"
        android:layout_height="45dp"
        android:layout_gravity="top"
        android:layout_margin="4dp"
        android:background="@color/gray"
        android:gravity="center"
        android:padding="10dp"
        android:text="No Contact Selected"
        android:textSize="20dp" />
</LinearLayout>

<EditText
    android:id="@+id/etPhoneNumber"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="2dp"
    android:gravity="center"
    android:hint="Person&apos;s Phone Number"
    android:padding="10dp" >
</EditText>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_margin="1dp"
        android:background="@color/burntorange"
        android:descendantFocusability="beforeDescendants"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android:orientation="horizontal"
        android:padding="1dp" >

        <ScrollView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/svEnterMessage"
            android:layout_width="269dp"
            android:layout_height="wrap_content"
            android:paddingBottom="4dp" >

            <EditText
                android:id="@+id/etTypeMessage"
                android:layout_width="260dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="2dp"
                android:layout_marginRight="4dp"
                android:layout_marginTop="4dp"
                android:background="@drawable/outline"
                android:hint="Type Message Here"
                android:minHeight="35dp"
                android:padding="6dp"
                android:textColor="@color/white"
                android:inputType="textMultiLine" >"
            </EditText>
        </ScrollView>

        <Button
            android:id="@+id/bSendText"
            android:layout_width="75dp"
            android:layout_height="36dp"
            android:layout_marginBottom="2dp"
            android:layout_marginLeft="2dp"
            android:background="@color/gray"
            android:text="Send"
            android:layout_gravity="bottom"
            android:textColor="@color/white" />

    </LinearLayout>

  </RelativeLayout>

</LinearLayout>

person Caleb    schedule 23.08.2012    source источник


Ответы (1)


Может кто-нибудь сказать мне, где в моем коде я говорю приложению начать это действие?

Похоже, он запускает приложение для обмена сообщениями по умолчанию:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("SMS Body", sms);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Если вы не хотите загружать приложение по умолчанию, что вы пытаетесь здесь сделать?

person Sam    schedule 23.08.2012
comment
Ну, я думаю, я использую приложение по умолчанию, но раньше, когда я нажимал кнопку «Отправить». Оно использовало приложение для отправки, но на самом деле никогда не выводило меня на экран. Он просто отправил его, сказал, что СМС отправлено, и все. Однако не могу понять, почему он изменился. (Все еще новичок в этом, очевидно: P) - person Caleb; 24.08.2012
comment
Ну, код в блоке try {} сразу после этого выглядит так, как будто он должен отправить SMS. Итак, мой вопрос: почему вы делаете и то, и другое? (Возможно, вы просто хотите удалить код sendIntent?) - person Sam; 24.08.2012
comment
О боже.... Ага. Вот оно. Просто пришлось удалить это. Должно быть, он добавил это намерение, когда экспериментировал со всем этим. Должно было быть очевидно, ха-ха. Что ж, большое спасибо, Сэм. Я медленно поправляюсь во всем этом. - person Caleb; 24.08.2012