Alarm via BoardCast Reciever Android


This tutorial might be helpful for leaning about the Alarm with Broadcast Receiver in android.
Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run-time once this event happens.  

A BroadcastReceiver object is only valid for the duration of the call toonReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active. 

If registering a receiver in your Activity.onResume() implementation, you should unregistered it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregistered inActivity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.  More detail about broadcast receiever Here.

Alarm Manager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted. 

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

There are two way we can registered and unregistered the broadcast receive.
1. Dynamic way
2. Static Way 

Dynamic way:- 

You can register a receiver dynamically via the Context.registerReceiver()method. You can also dynamically unregister receiver by usingContext.unregisterReceiver() method.

Static Way:-

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file. 
For Register
?
1
2
3
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
For UnRegister
?
1
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
?
1
2
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

main_activity.xml

?
1
2
3
4
5
6
7
8
9
10
11
<linearlayout android:gravity="center|top" android:id="@+id/LinearLayout1" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" 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=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
    <button android:id="@+id/button_startalarm" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Start Reapeat Alarm">
    </button><button android:id="@+id/button_cancelalarm" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Cancel Alarm">
    </button><button android:id="@+id/button_enablebr" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Enable BR">
    </button><button android:id="@+id/button_disablebr" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Disable BR">
</button></linearlayout>

MainActivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.sunil.br;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
    private Button btnstartalarm=null;
    private Button btncancelalarm=null;
    private Button btnenablebr=null;
    private Button btndiablebr=null;
    AlarmManager amanager=null;
    PendingIntent pi=null;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        btnstartalarm = (Button)findViewById(R.id.button_startalarm);
        btncancelalarm = (Button)findViewById(R.id.button_cancelalarm);
        btnenablebr = (Button)findViewById(R.id.button_enablebr);
        btndiablebr = (Button)findViewById(R.id.button_disablebr);
         
        btnstartalarm.setOnClickListener(this);
        btndiablebr.setOnClickListener(this);
        btncancelalarm.setOnClickListener(this);
        btnenablebr.setOnClickListener(this);
         
    }
    @Override
    public void onClick(View arg0) {
         
        if(arg0==btnstartalarm)
        {
            amanager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
            Intent intent= new  Intent(this, AlarmManagerBR.class);
            pi=PendingIntent.getBroadcast(this, 0, intent, 0);
             //After after 2 seconds
            amanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*4, pi);
            Toast.makeText(this, "Start Repating Alarm", Toast.LENGTH_SHORT).show();
             
        }
        else if (arg0==btncancelalarm) {
             
            amanager.cancel(pi);
            Toast.makeText(this, "Canceled Alarm", Toast.LENGTH_SHORT).show();
        }
         
        else if(arg0==btnenablebr){
             
             ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
             PackageManager pm = this.getPackageManager();
             pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
             Toast.makeText(this, "Enable Boradcast Reciever", Toast.LENGTH_SHORT).show();
        }
        else if (arg0==btndiablebr) {
             
             ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
             PackageManager pm = this.getPackageManager();
             pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
             Toast.makeText(this, "Diable Boradcast Reciever", Toast.LENGTH_SHORT).show();
        }
    }
}

AlarmManagerBR.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.sunil.br;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmManagerBR extends BroadcastReceiver{
    @SuppressLint("SimpleDateFormat")
    @Override
    public void onReceive(Context arg0, Intent arg1) {
         
        StringBuilder sb=new StringBuilder();
        SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss a");
        sb.append(format.format(new Date()));
        Toast.makeText(arg0, sb, Toast.LENGTH_SHORT).show();
    }
}

Manifest.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<manifest android:versioncode="1" android:versionname="1.0" package="com.sunil.br" xmlns:android="http://schemas.android.com/apk/res/android">
    <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:label="@string/app_name" android:name="com.sunil.br.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <receiver android:name="com.sunil.br.AlarmManagerBR"></receiver>
    </application>
</uses-sdk></manifest>


Comments

Popular posts from this blog