Friday 19 April 2013

Set Alarm on specified time using Broadcast reciever in Android

Alarm.java

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class Alarm extends Activity {

    TimePicker TimePicker;
    Button Setalarm;

    TimePickerDialog timePickerDialog;

    final static int RQS_1 = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);

        Setalarm = (Button) findViewById(R.id.Setalarm);
        Setalarm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                openTimePickerDialog(false);

            }
        });

    }

    private void openTimePickerDialog(boolean is24r) {
        Calendar calendar = Calendar.getInstance();
        timePickerDialog = new TimePickerDialog(Alarm.this, onTimeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), is24r);
        timePickerDialog.setTitle("Set Alarm");

        timePickerDialog.show();

    }

    OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

            calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calSet.set(Calendar.MINUTE, minute);
            calSet.set(Calendar.SECOND, 0);
            calSet.set(Calendar.MILLISECOND, 0);

            if (calSet.compareTo(calNow) <= 0) {

                calSet.add(Calendar.DATE, 1);
            }

            setAlarm(calSet);
        }
    };

    private void setAlarm(Calendar targetCal) {

        //
        Toast.makeText(Alarm.this, "Alarm is set at" + targetCal.getTime(),
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), RQS_1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
                pendingIntent);

    }

}




AlarmReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Toast.makeText(arg0, "Your Time is up!!!!!", Toast.LENGTH_LONG).show();

    }

}


activity_alarm.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/Setalarm"
        android:layout_width="117dp"
        android:layout_height="106dp"
        android:background="@drawable/alarm" />

    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarm_manager"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarm_manager.Alarm"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>



Screenshot

41 comments:

  1. Alarm is not working when the app is closed. How to fix this please help.

    ReplyDelete
  2. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    Digital Marketing Training in Pune

    ReplyDelete
  3. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.
    Click here:
    python training in Bangalore
    Click here:
    python training in Bangalore

    ReplyDelete
  4. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  5. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    python training in chennai
    python training in chennai
    python training in Bangalore

    ReplyDelete
  6. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Devops training in sholinganallur

    ReplyDelete
  7. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.

    java online training | java training in pune

    java training in chennai | java training in bangalore

    ReplyDelete
  8. It would have been the happiest moment for you,I mean if we have been waiting for something to happen and when it happens we forgot all hardwork and wait for getting that happened.


    angularjs Training in chennai
    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    ReplyDelete
  9. Useful information.I am actual blessed to read this article.thanks for giving us this advantageous information.I acknowledge this post.and I would like bookmark this post.Thanks

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  10. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
    Python training in marathahalli | Python training institute in pune | Python training in IndiraNagar

    ReplyDelete
  11. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  12. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    blue prism Training in Electronic City

    ReplyDelete
  13. This is the best explanation about this topic, it is very useful and valuable content to all readers. I am always following your post, please updates more different posts.keep it up.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.
    tally course in chennai

    hadoop course in chennai

    sap course in chennai

    oracle course in chennai

    angular js course in chennai

    ReplyDelete
  16. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    salesforce course in chennai

    software testing course in chennai

    robotic process automation rpa course in chennai

    blockchain course in chennai

    devops course in chennai

    ReplyDelete
  17. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    Spoken english classes in chennai | Communication training

    ReplyDelete
  18. Learn Big Data for the best career opportunities with Infycle Technologies. Infycle Technologies is the best Big Data training institute in Chennai, providing courses for the Big Data Training in Chennai in 100% hands-on practical training with expert trainers in the field. Apart from the training, the mock interviews will be arranged for the students, so that they can set their career without any struggle. Of all that, 100% placement assurance will be given here. For the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.

    top big data training institute in Chennai

    ReplyDelete


  19. This post is so interactive and informative.keep update more information...
    Tally Course in Chennai
    Tally Classes in Chennai
    Online Tally Course

    ReplyDelete
  20. Infycle Technologies, the best software training institute in Chennai offers the Data Science Certification in Chennai for students, tech professionals, and freshers. Apart from the Data Science Course, other courses such as Python, Cyber Security, Oracle, Java, Hadoop, Selenium, Android, and iOS Development, Big Data will also be trained with 100% hands-on training. After the completion of training, the students will be sent for placement interviews in the core MNC's. Dial 7502633633 to get more info and a free demo.

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Grab the Digital Marketing Training in Chennai from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, Oracle etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete