Monday, December 16, 2013

Android Alarm Manager Example | How to Start and Stop Alarm Manager in Android | Notification Manager Example in Android

Hello Friend,

Today I am going to share code for "Create Alarm Manager in Android". And Notification Manager with sound and vibration.


EDIT:stop was not working


1)MainActivity-


package com.manish.alarmmanager;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
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;

/**
 *
 * @author manish
 *
 */

public class MainActivity extends Activity implements OnClickListener{

Button btnStartAlarm,btnStopAlarm;
Context context;
static PendingIntent pendingIntent;
static AlarmManager alarmManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=MainActivity.this;


Intent intentsOpen = new Intent(this, AlarmReceiver.class);
intentsOpen.setAction("com.manish.alarm.ACTION");
pendingIntent = PendingIntent.getBroadcast(this,111, intentsOpen, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);


btnStartAlarm=(Button)findViewById(R.id.button1);
btnStopAlarm=(Button)findViewById(R.id.button2);

btnStartAlarm.setOnClickListener(this);
btnStopAlarm.setOnClickListener(this);

}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==btnStartAlarm){
fireAlarm();
}
if(v==btnStopAlarm){
stopAlarm();
}
}
public void fireAlarm() {
/**
* call broadcost reciver
*/
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10000, pendingIntent);


}
public void stopAlarm(){
alarmManager.cancel(pendingIntent);



}


}


3)OutPut.java

package com.manish.alarmmanager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class OutPut extends Activity {
TextView textmessage;
String stringValue;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);

textmessage = (TextView) findViewById(R.id.textView1);

Intent intent = getIntent();
stringValue = intent.getStringExtra("content");
textmessage.setText(stringValue);
System.out.println(stringValue);

}
}

4)Manifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.VIBRATE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.manish.alarmmanager.OutPut" />

        <receiver android:name=".AlarmReceiver" >
            <intent-filter>
                <action android:name="com.manish.alarm.ACTION" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

DOWNLOAD ZIP CODE

Thanks!

17 comments :

  1. great, thanks... i will try

    ReplyDelete
  2. thank you for this tutorial

    can you please teach us how to stop service at specific time using alarm manager or other technique

    ReplyDelete
    Replies
    1. Inside fireAlarm(); method call stopServices();
      And don't use repeating because services will stop only ones.

      Delete
  3. fantastic! good job my friend

    ReplyDelete
  4. Superb bro, saved my life :) (y)

    ReplyDelete
  5. how can i do this when the date of alarm are stored in the database ?

    ReplyDelete
    Replies
    1. Look at this line- alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10000, pendingIntent);

      instead of calendar.getTimeInMillis() pass your database time in Calender format.

      Delete
  6. hello.code is working properly.but when i close application,alarmmanager class also stops to send broadcast.and no notification is displaying.what is solution for that?

    ReplyDelete
    Replies
    1. is it really? which phone?
      I don't know what is the reason, anyway please check your Alarm Manager is calling to Broadcast Receiver and receiver generating notification.

      Delete
  7. manish. would u help me please with this code. i already try it and it's always output my program has stopped. when i change generateNotification with this code :
    Toast.makeText(context,"Welcome = ",Toast.LENGTH_SHORT).show();
    it works.
    but when i change my code into this one :
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.notification, "try to notif you", System.currentTimeMillis());
    Intent notificationIntent = new Intent(context, Main2Activity.class);
    PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
    but this code always has stopped.
    thx for help before

    ReplyDelete

Note: Only a member of this blog may post a comment.