如何在给定的时间和日期安排消息?

时间:2017-11-01 07:42:04

标签: android scheduled-tasks smsmanager

我想在Android中使用日期选择器和时间选择器在给定的时间和日期安排一条消息,任何帮助都会非常感激。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mEditText = (EditText) findViewById(R.id.username);
    msendSms = (EditText) findViewById(R.id.sendssms);
    mEditText.setOnTouchListener(new RightDrawableOnTouchListener(mEditText) {
        @Override
        public boolean onDrawableTouch(MotionEvent event) {
            mEditText.setText("");
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, PICK_CONTACT);
            return true;
        }
    });

    pickdate = (Button) findViewById(R.id.pickdate);
    pickdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            datepicker();
        }
    });
    pickTime = (Button) findViewById(R.id.pickTime);
    pickTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    pickTime.setText( selectedHour+ ":" +selectedMinute);
                }
            }, hour, minute,false);
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();
        }
    });


    ScheduleMesage = (Button) findViewById(R.id.scheduleMsg);
    ScheduleMesage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            phoneNo = mEditText.getText().toString().trim();
            message = msendSms.getText().toString().trim();
            SmsManager smsManager=SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();

        }
    });
}

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (PICK_CONTACT):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = managedQuery(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                    String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                    if (hasPhone.equalsIgnoreCase("1")) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                        phones.moveToFirst();
                        String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        cNumber = cNumber.replaceAll("[\\D]", "");
                        if (cNumber.length() >= 10) {
                            cNumber = cNumber.substring(cNumber.length() - 10);
                        }

                        Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();

                        String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

                        mEditText.setText(nameContact + " " + cNumber);
                    }
                }
            }
    }
}


@TargetApi(Build.VERSION_CODES.N)
private void datepicker() {
    Calendar calendar = Calendar.getInstance();
    final int mYear = calendar.get(Calendar.YEAR);
    final int mMonth = calendar.get(Calendar.MONTH);
    final int mDay = calendar.get(Calendar.DAY_OF_MONTH);

    datePickerDialog = new DatePickerDialog(MainActivity.this,
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                     time = "" + i + "-" + i2 + "-" + (i1 + 1);
                    pickdate.setText(time);
                }
            }, mYear, mMonth, mDay);

    datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
    pickdate.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            datePickerDialog.show();
            return false;
        }
    });

    pickdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datepicker();
        }

    });
}

我正在使用上面的代码立即发送短信我可以发送短信但是  我需要在预定的时间发送短信。

1 个答案:

答案 0 :(得分:0)

嘿,你可以使用闹钟管理器

即样品在5秒后变成按钮红色

public void SetAlarm()
    {
        final Button button = buttons[2]; // replace with a button from your own UI
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override public void onReceive( Context context, Intent _ )
            {
                // you can send sms here
                button.setBackgroundColor( Color.RED );
                context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
            }
        };

        this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );

        PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
        AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

        // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
        manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
    }