文本消息未发送到数字列表,但仅在指定一个数字时发送

时间:2017-10-20 12:46:19

标签: java android arraylist smsmanager

我正在尝试构建一个应用程序,用户可以将location发送到sqlitedatabase中存储的电话号码。我测试了用户可以将location作为文本消息发送到一个电话号码的应用程序,但是现在当我尝试创建list个数字并将其作为参数传递给{不会发送sendTextMessage smsManager作为短信的location方法。到目前为止,我已经尝试了下面给出的代码,

代码

public class Gps4Activity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener {

    private static final String LOG_TAG = "PlacesAPIActivity";
    private static final int GOOGLE_API_CLIENT_ID = 0;
    private GoogleApiClient mGoogleApiClient;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
    private TextView display;
    private Button location_button,contacts_button;
    //String number="xxxxxxxxxx";
    ArrayList<String> numbers;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps4);
        numbers=new ArrayList<>();
        db = new UserDatabase(this).getReadableDatabase();
        location_button=(Button)findViewById(R.id.show_button);
        contacts_button=(Button)findViewById(R.id.view_button);
        display=(TextView)findViewById(R.id.location_textview);

        mGoogleApiClient = new GoogleApiClient.Builder(Gps4Activity.this)
                .addApi(Places.PLACE_DETECTION_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .build();

        location_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGoogleApiClient.isConnected()) {
                    if (ActivityCompat.checkSelfPermission(Gps4Activity.this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(Gps4Activity.this,
                                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                                PERMISSION_REQUEST_CODE);
                        ActivityCompat.requestPermissions(Gps4Activity.this,
                                new String[]{Manifest.permission.SEND_SMS},
                                MY_PERMISSIONS_REQUEST_SEND_SMS);
                    }
                }
                callPlaceDetectionApi();
            }
        });

        contacts_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Gps4Activity.this,DetailsActivity.class);
                startActivity(intent);
            }
        });
    }

    public ArrayList<String> getContacts(){

        Cursor cursor=db.rawQuery("SELECT * FROM "+UserDatabase.TABLE_NAME,null);
        while (cursor.moveToNext()){
            String contact=cursor.getString(cursor.getColumnIndex(UserDatabase.NUMBER));
            numbers.add(contact);
        }
        return numbers;
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(LOG_TAG, "Google Places API connection failed with error code: "
                + connectionResult.getErrorCode());

        Toast.makeText(this,
                "Google Places API connection failed with error code:" +
                        connectionResult.getErrorCode(),
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    callPlaceDetectionApi();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again.", Toast.LENGTH_LONG).show();
                    return;
                }
                break;

        }
    }

    private void callPlaceDetectionApi() throws SecurityException {
        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    Log.i(LOG_TAG, String.format("Place '%s' with " +
                                    "likelihood: %g",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));
                    display.setText(placeLikelihood.getPlace().getAddress().toString());
                    messageSending(placeLikelihood.getPlace().getAddress().toString());
                    break;
                }
                likelyPlaces.release();

            }
        });
    }

    public void messageSending(String message){
        SmsManager smsManager = SmsManager.getDefault();
//        smsManager.sendTextMessage(number, null, message, null, null);
        getContacts();
        smsManager.sendTextMessage(String.valueOf(numbers),null,message,null,null);
        Toast.makeText(getApplicationContext(), "SMS sent."+String.valueOf(numbers),
                Toast.LENGTH_LONG).show();
    }
}

当我尝试使用一个电话号码测试应用程序时,评论的行就是那些。另外,假设最初在sqlitedatabase中只有一个电话号码,我点击location_button多次arraylist增加它的大小。例如,如果arraylist下次点击[xxxxxx]location_button包含元素arraylist,则[xxxxxx,xxxxxx]现在会/// @brief Top-level root element "":BODY /// @brief "":BODY is a complexType. /// /// class BODY operations: /// - BODY* soap_new_BODY(soap*) allocate and default initialize /// - BODY* soap_new_BODY(soap*, int num) allocate array and default initialize values /// - BODY* soap_new_req_BODY(soap*, ...) allocate, set required members /// - BODY* soap_new_set_BODY(soap*, ...) allocate, set all public members /// - BODY::soap_default(soap*) default initialize members /// - int soap_read_BODY(soap*, BODY*) deserialize from a stream /// - int soap_write_BODY(soap*, BODY*) serialize to a stream /// - BODY* BODY::soap_dup(soap*) returns deep copy of BODY, copies the (cyclic) graph structure when a context is provided, or (cycle-pruned) tree structure with soap_set_mode(soap, SOAP_XML_TREE) (use soapcpp2 -Ec) /// - BODY::soap_del() deep deletes BODY data members, use only after BODY::soap_dup(NULL) (use soapcpp2 -Ed) class BODY { public: // BEGIN CHOICE <xs:choice maxOccurs="2"> $int __size_BODY 0:2; class ___union_BODY { $int __union_BODY ; ///< Union union_BODY selector: set to SOAP_UNION_union_BODY_<fieldname> /// Union for choice in BODY. union union_BODY { /// Element reference ":""":LANE. LANE* LANE_ 0; ///< Optional element. /// Vector of std::shared_ptr<DEVICE> element refs of length 0..unbounded. std::vector<std::shared_ptr<DEVICE> > *DEVICE_ 0; /// Element reference ":""":TRIP. TRIP* TRIP_ 0; ///< Optional element. /// Element reference ":""":CASH_DISPOSAL. CASH_USCOREDISPOSAL* CASH_USCOREDISPOSAL_ 0; ///< Optional element. /// Element reference ":""":ISSUE. ISSUE* ISSUE_ 0; ///< Optional element. /// Element reference ":""":SHIFT. SHIFT* SHIFT_ 0; ///< Optional element. /// Element reference ":""":SALE_RECHARGE. SALE_USCORERECHARGE* SALE_USCORERECHARGE_ 0; ///< Optional element. /// Element reference ":""":LIFE. LIFE* LIFE_ 0; ///< Optional element. /// Element reference ":""":OBSERVATION. OBSERVATION* OBSERVATION_ 0; ///< Optional element. /// Element reference ":""":SURVEY_RESPONSE. SURVEY_USCORERESPONSE* SURVEY_USCORERESPONSE_ 0; ///< Optional element. /// Element reference ":""":BLOCK_USER. BLOCK_USCOREUSER* BLOCK_USCOREUSER_ 0; ///< Optional element. /// Element reference ":""":ACTION. ACTION* ACTION_ 0; ///< Optional element. /// Element reference ":""":SPECIALACTION. SPECIALACTION* SPECIALACTION_ 0; ///< Optional element. /// Element reference ":""":TEXT. TEXT* TEXT_ 0; ///< Optional element. /// Element reference ":""":RESEND. RESEND* RESEND_ 0; ///< Optional element. /// Element reference ":""":TRIP_RESEND. TRIP_USCORERESEND* TRIP_USCORERESEND_ 0; ///< Optional element. /// Element reference ":""":DISPLAY. DISPLAY* DISPLAY_ 0; ///< Optional element. /// Element reference ":""":DEBT_CANCELLATION. DEBT_USCORECANCELLATION* DEBT_USCORECANCELLATION_ 0; ///< Optional element. } _BODY ; } *_BODY ; // END OF CHOICE /// A handle to the soap struct context that manages this instance when instantiated by a context or NULL otherwise (automatically set). struct soap *soap ; };

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

由于sendTextMessage()方法一次只能获取一个数字,因此您需要为列表中的每个数字执行此方法。

据说你应该“循环”List。像这样:

for (String number : numbers) {
    smsManager.sendTextMessage(numbers, null, message, null, null);
}

它基本上是说:

“好吧,让我们先拿一号,把文字消息发送到第一,我会一直这样做,直到我完成。”