0

I am trying to generate an alarm on a scheduled time in future. Below is the code

MainActivity.java

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.util.GregorianCalendar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).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.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void scheduleAlarm(View V)
    {
        // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
        // we fetch  the current time in milliseconds and added 1 day time
        // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day
        Long time = new GregorianCalendar().getTimeInMillis()+60*60*1000;

        // create an Intent and set the class which will execute when Alarm triggers, here we have
        // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
        // alarm triggers and
        //we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
        Intent intentAlarm = new Intent(this, AlarmReciever.class);

        // create the object
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        //set the alarm for particular time
        alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
        Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();

    }
}

AlarmReceiever.java

public class AlarmReciever extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // TODO Auto-generated method stub


        // here you can start an activity or service depending on your need
        // for ex you can start an activity to vibrate phone or to ring the phone

       String message="Hi I will be there later, See You soon";// message to send

        // Show the toast  like in above screen shot
        Log.d("Alarm",message);
        Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
    }

}

content_main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Alarm Manager Example"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_marginTop="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Schedule The Alarm"
        android:onClick="scheduleAlarm"/>

</LinearLayout>

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="voice1.xxx.com.alarmcheck2" >

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AlarmReciever"/>
    </application>

</manifest>

I am trying to generate the alarm after one minute, but unfortunately nothing is happening. What have I done wrong here? Also, how can I make sure my schedule will work even after a phone restart/ turned off then turned on?

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 1
    Did you register your Receiver in the manifest? Also, `60*60*1000` milliseconds is an hour. – Mike M. Jun 29 '16 at 07:32
  • @MikeM.: Sorry, I have posted the manifest now. I am new to this, so I did but not sure whether it is correct. – PeakGen Jun 29 '16 at 07:34
  • I was editing my comment. You may need to refresh the page. If you're testing, you may just want to set the time for now. – Mike M. Jun 29 '16 at 07:36
  • @MikeM.: Thanks, it did work. Also, how can I set the time to something line 1st of July 9.30AM and make sure the alarm will work? (You know, the user will turn his phone on and off, he will not keep the phone on forerver, so how to address this issue as well?) – PeakGen Jun 29 '16 at 07:40
  • In case of restarting the phone, the alarm set using alarm manager will be reset. Hence you might need to register a receiver for Boot Complete & set the alarm again from onReceive. – Sujay Jun 29 '16 at 07:45
  • @sJy: OK, how to do that? – PeakGen Jun 29 '16 at 07:45
  • The `Calendar#set()` method allows you to set specific date/time components. To reset your alarm after rebooting, you'll need to implement a boot Receiver, as described in [this post](http://stackoverflow.com/questions/12034357). Also, you don't need the `SET_ALARM` permission for this. – Mike M. Jun 29 '16 at 07:46
  • See answer from @Binary Devs below – Sujay Jun 29 '16 at 07:46

2 Answers2

1

I think you not called your scheduleAlarm() method any where in the code above. And for schedule work even after a phone restart/ turned off then you have to listen BOOT_COMPLETED event. For listen bootcompile the code is given below:-

You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.

<receiver android:name=".BootCompletedReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Make sure also to include the completed boot permission.

BroadcastReceiver-

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootCompletedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

    }
}
  • Register your Receiver in the manifest like this- `` –  Jun 29 '16 at 07:48
  • Thank you. By looking at code, can you suggest what to include in this `onRecieve` of `ServiceStarter` ? – PeakGen Jun 29 '16 at 07:50
  • @PeakGen do this :- `if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { // your code.......... }` –  Jun 29 '16 at 07:55
  • I am not clear, what you are saying is that I have to move the code inside `scheduleAlarm()` into `onRecieve()`? – PeakGen Jun 29 '16 at 07:59
  • I am not taking about your alarm receiver write now, the codes which i share is to perform any action after fter a phone restart/ turned off then turned on –  Jun 29 '16 at 08:02
  • Now for your alarm -- Register your Receiver in the manifest like this- and call your scheduleAlarm() function in your code any where.... –  Jun 29 '16 at 08:04
  • Hope you understand now @PeakGen –  Jun 29 '16 at 08:08
  • I think I do, Thanks. I am trying and will let you know. – PeakGen Jun 29 '16 at 08:10
1

I tried your code and made some adjustments and it was working for me

public void scheduleAlarm() {
        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        final PendingIntent wakeupIntent = PendingIntent.getBroadcast(this, 0,
                new Intent(this, AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 60); // first time
        long frequency = 6* 1000; // in ms
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, wakeupIntent);

    }

Try this.

Ankit Khare
  • 1,345
  • 11
  • 30