使用共享首选项保存字符串并将保存的字符串作为短信发送到另一个号码

时间:2014-09-11 08:10:44

标签: android

我必须将我自己的手机号码作为sms发送到另一个号码xxx我使用了getLine1number()函数它返回null,因为它没有存储在sim中的号码。 我正在尝试使用共享首选项输入我的号码保存一次并将该号码作为短信发送到另一个号码..怎么可能?我的代码是

package com.example.mobile;

import android.os.Bundle;
import android.telephony.SmsManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;

public class MainActivity extends Activity {

EditText editText;
Button saveButton;

String mStoredNumber;

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

    editText = (EditText) findViewById(R.id.editText1);
    saveButton = (Button) findViewById(R.id.button1);

    saveButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
                    savePreferences("storedNumber", editText.getText().toString());
                    Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();

            // Load number and send to phoneNo
            loadSavedPreferences();
            // Now the stored number is in mStoredNumber
            String phoneNo = "123";

            TelephonyManager tManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String Imsi=tManager.getSubscriberId();
            String Imei=tManager.getDeviceId();

            try{
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, "IMSI,IMEI and phone number - "+Imsi+","+Imei+","+mStoredNumber+"", null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!",
                        Toast.LENGTH_LONG).show();
            }
            catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                    "SMS faild, please try again later!",
                    Toast.LENGTH_LONG).show();
                e.printStackTrace();
              }

    loadSavedPreferences();
}
     });
}

private void loadSavedPreferences() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);

    String number = sharedPreferences.getString("storedNumber", "YourNumber");
    mStoredNumber = number;

    editText.setText(number);
}

private void savePreferences(String key, String value) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();

}
}

我的xml代码是

<?xml version="1.0"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@+id/linearLayout1" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical">

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/enter_your_number_" 
    android:inputType="number">

    <requestFocus />
</EditText>

<Button android:id="@+id/button1" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/save"/>

</LinearLayout>

号码正在保存,当我再次打开应用程序时,它没有显示顶部的号码再次要求输入号码。第二次当我打开应用程序时,我不应该得到保存按钮。 请提出解决方案。

3 个答案:

答案 0 :(得分:1)

修改 如果您希望在不按下按钮的情况下进行此操作,只需将SMS发送部件移至onCreate。

<强> MainActivity.java

public class MainActivity extends Activity {

    EditText editText;
    Button saveButton;

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

        // Find editText and saveButton
        editText = (EditText) findViewById(R.id.editText1);
        saveButton = (Button) findViewById(R.id.button1);

        // Try to send existing number via SMS
        if (sendSMS()) {
            // Successful, exit the app
            finish();
        }

        // If we are here, this means sendSMS returned false 
        // if the phone number was saved before, it is now displayed in editText
        // add an onClickListener to the save button

        saveButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                // Save number and send it
                savePhoneNumber(editText.getText().toString());
                sendSMS();
            }
        });

    }

    /* Sends saved phone number + IMEI, IMSI via SMS, returns true if successful */
    private boolean sendSMS() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);

        String number = sharedPreferences.getString("storedNumber", "");
        if (number == "") {
            // No saved number, ask user to enter it and save it
            Toast.makeText(this, "Enter your phone number and tap on Save", Toast.LENGTH_SHORT).show();
            return false;
        }
        else {
            // There is saved phone number, add it to editText for later use (if SMS sending fails)
            editText.setText(number);
            String phoneNo = "123";
            TelephonyManager tManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String Imsi=tManager.getSubscriberId();
            String Imei=tManager.getDeviceId();
            try{
                SmsManager smsManager = SmsManager.getDefault();
                String message = "IMSI, IMEI and phone number: "+Imsi+", "+Imei+", "+number;
                smsManager.sendTextMessage(phoneNo, null, message, null, null);
                Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
                return true;
            }
            catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                    "SMS failed, please try again later!", Toast.LENGTH_LONG).show();
                e.printStackTrace();
                return false;
            }
        }
    }

    /* Stores phone number in the default shared prefs. */
    private void savePhoneNumber(String value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString("storedNumber", value);
        editor.commit();
    }
}

activity_main.xml应该包含一个EditText(带有id = editText1)和一个Button(id = button1)

答案 1 :(得分:0)

我猜是有一些错误。但首先,您要发送一个硬编码字符串"storedNumber",而不是从sharedpreferences / textbox获取字符串。

将您发送的字符串更改为动态字符串。如下所示 - 从文本框中加载。

phoneNo也被硬编码为"123",这似乎不切实际。

            String phoneNo = "123";
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, editText.getText().toString(), null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!",
                        Toast.LENGTH_LONG).show();

答案 2 :(得分:0)

编辑回答以包括网络选择:

package com.example.mobnet;

import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;



public class MainActivity extends ActionBarActivity {


 EditText editText;
 Button saveButton;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
    startActivity(intent);

    // Find editText and saveButton
    editText = (EditText) findViewById(R.id.editText1);
    saveButton = (Button) findViewById(R.id.button1);

    // Try to send existing number via SMS
    if (sendSMS()) {
        // Successful, exit the app
        finish();
    }

    // If we are here, this means sendSMS returned false 
    // if the phone number was saved before, it is now displayed in editText
    // add an onClickListener to the save button

    saveButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            // Save number and send it
            savePhoneNumber(editText.getText().toString());
            sendSMS();
        }
    });

}

/* Sends saved phone number + IMEI, IMSI via SMS, returns true if successful */
private boolean sendSMS() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);

    String number = sharedPreferences.getString("storedNumber", "");
    if (number == "") {
        // No saved number, ask user to enter it and save it
        Toast.makeText(this, "Enter your phone number and tap on Save after selecting network", Toast.LENGTH_SHORT).show();
        return false;
    }
    else {
        // There is saved phone number, add it to editText for later use (if SMS sending fails)
        editText.setText(number);
        String phoneNo = "108";
        TelephonyManager tManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        String Imsi=tManager.getSubscriberId();
        String Imei=tManager.getDeviceId();
        try{
            SmsManager smsManager = SmsManager.getDefault();
            String message = "IMSI, IMEI and phone number: "+Imsi+", "+Imei+", "+number;
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
            return true;
        }
        catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                "SMS failed, please try again later!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            return false;
        }
    }
}

/* Stores phone number in the default shared prefs. */
private void savePhoneNumber(String value) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putString("storedNumber", value);
    editor.commit();
}
}