SmsManager and AllarmAlert doesn't works

42 views Asked by At

my code to send sms scheduled doesn't works, the sms doesn't sent after 10 seconds.WHY?

i show you my code:

MainActivity:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void scheduleAlarm(View V){
        //Long time= new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
        //Long time= new GregorianCalendar().getTimeInMillis()+10000;
        //Long time= System.currentTimeMillis() + 10000;

        Intent intentAlarm= new Intent(this, AlarmReceiver.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        //alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));

        Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String phoneNumberReciver="1234556";
        String message="blablabla";
        android.telephony.SmsManager sms= SmsManager.getDefault();
        sms.sendTextMessage(phoneNumberReciver, null, message, null, null);
        Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG);

    }

}

Thanks in advance!

2

There are 2 answers

1
Sadiq Md Asif On

use this one to set alarm at 10 seconds!

  alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000,
                            PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
3
Divyesh Patel On

try this and also put your send sms code to intent service:

if (SDK_INT < Build.VERSION_CODES.KITKAT) {
            alarmManager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+10000, pendingIntent);

        }
        else if (Build.VERSION_CODES.KITKAT <= SDK_INT  && SDK_INT < Build.VERSION_CODES.M) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+10000,pendingIntent);

        }
        else if (SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+10000,pendingIntent);

        }