Thursday, August 4, 2016

Scheduling Task Using AlarmManager in Android


Hi .... Dear All ....  Today I am uploading a superb example of Scheduling of Task using AlarmManager.


AlarmManager
"Alarms (based on the AlarmManager class) give you a way to perform time-based operations outside the lifetime of your application". 
An example can be thought of as downloading the weather report once in a day or twice in a day and notifying the user.
Characteristics of Alarms:
Alarms can let one to fire Intents at set times or in certain time intervals.
Alarms can be used together with the broadcast receiver to notifies user.

Alarms can triggers even if device falls asleep because they run outside the application.

To implement scheduling using AlarmManager we have to do following
Create MainActivity -   In this class we will schedule the alarm to be triggered at particular time.
Create Alarm Receiver – When the alarm triggers at particular time , this class will receive the alarm and take the action defined.
üThis class extends BroadcastReceiver and overrides onReceive() method.
üYou can start in this method any service as well as any action like ringing,SMS sending ,Vibrate phone.
üYou should add permission in manifest file like
<uses-permission  android:name="com.android.alarm.permission.SET_ALARM"/> 
üAlso register to Alarm Receiver
In this example you can set alarm after a specified time interval in secs. After your specified time interval your device will vibrate.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box
@@@@ please add read write permission in manifest file like
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

A. Layout will be like  

     

B. Layout xml file

activity_main.xml file is as 

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.exam.ravi.alarmmanager.MainActivity">
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="start alarm"

        android:id="@+id/stbutton"

        android:onClick="startAlert"

        android:layout_below="@+id/editText"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="35dp" />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:inputType="phone"

        android:hint="EnterTime In Seconds Only"

        android:id="@+id/editText"

        android:gravity="center"

        android:layout_marginTop="50dp"

        android:layout_below="@+id/textView"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true" />

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Enter Time To Set an Alarm"

        android:id="@+id/textView"

        android:textSize="20sp"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true" />

</RelativeLayout>

C. Java Code

MainActivity.java is as 

package com.exam.ravi.alarmmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity
 {
     EditText text;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
    Intent intent;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.editText);


    }

    public void startAlert(View view) {
        if (!text.getText().toString().equals("")) {
            int i = Integer.parseInt(text.getText().toString());
            intent = new Intent(this, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(
                    this.getApplicationContext(), 1, intent, 
                             PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP,
              Calendar.getInstance().getTimeInMillis() + (i * 1000), pendingIntent);
            Toast.makeText(this, "Alarming after  " + i + " seconds",
                    Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(this,"Please enter  time ",Toast.LENGTH_SHORT).show();
        }

    }

 }

AlarmReceiver is as 

package com.exam.ravi.alarmmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Time Up... Now Vibrating !!!",
                Toast.LENGTH_LONG).show();
        Vibrator vibrator = (Vibrator) context
                .getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(5000);
    }
}

No comments:

Post a Comment