Creating Notification with AlarmManager using Service, AutoStart and UserSettings

In this blog post, I would like to explain how to code Notification with AlarmManager using Service, AutoStart on Reboot and Settings screen for User.

1) Create SettingActivity.java class and copy the below code.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

public class SettingActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
 super.onCreate(savedInstanceState);

 // Display the fragment as the main content.
 if (savedInstanceState == null)
 getFragmentManager().beginTransaction().add(android.R.id.content, new PrefFragment()).commit();
}

public static class PrefFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
{
 Context cont;
 Preference cbp1, cbp2, cbp3, cbp4, cbp5;
 SharedPreferences prefs;
 MyScheduledReceiver mSH = new MyScheduledReceiver();
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);

 cont = getActivity();
 prefs = PreferenceManager.getDefaultSharedPreferences(cont);
 prefs.registerOnSharedPreferenceChangeListener(this);
 addPreferencesFromResource(R.xml.user_setting);
 cbp1 = (Preference)findPreference("NotiOnOff");
 cbp2 = (Preference)findPreference("VibrateOnOff");
 cbp3 = (Preference)findPreference("LightOnOff");
 cbp4 = (Preference)findPreference("SoundOnOff");
 cbp5 = (Preference)findPreference("isAutoStartEnabled");

 getNotifiSetting();
 
 cbp1.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

 @Override
 public boolean onPreferenceChange(Preference preference,
 Object newValue) {
 // TODO Auto-generated method stub
 if ((Boolean) newValue) {
 mSH.SetAlarmR(cont);
 } else {
 mSH.CancelAlarmR(cont);
 }
 return true;
 }
 });

 }
 
 // String
 public static String Read(Context context, final String key) {
 SharedPreferences pref = PreferenceManager
 .getDefaultSharedPreferences(context);
 return pref.getString(key, "");
 }

 public static void Write(Context context, final String key,
 final String value) {
 SharedPreferences settings = PreferenceManager
 .getDefaultSharedPreferences(context);
 SharedPreferences.Editor editor = settings.edit();
 editor.putString(key, value);
 editor.commit();
 }

 // Boolean
 public static boolean ReadBoolean(Context context, final String key,
 final boolean defaultValue) {
 SharedPreferences settings = PreferenceManager
 .getDefaultSharedPreferences(context);
 return settings.getBoolean(key, defaultValue);
 }

 public static void WriteBoolean(Context context, final String key,
 final boolean value) {
 SharedPreferences settings = PreferenceManager
 .getDefaultSharedPreferences(context);
 SharedPreferences.Editor editor = settings.edit();
 editor.putBoolean(key, value);
 editor.commit();
 }
 
 @Override
 public void onSharedPreferenceChanged(
 SharedPreferences sharedPreferences, String key) {
 // TODO Auto-generated method stub
 getNotifiSetting();
 
 Editor editor = PreferenceManager.getDefaultSharedPreferences(cont).edit();
 editor.putBoolean("NotifiOnOff", prefs.getBoolean("NotiOnOff", true)); 
 editor.commit();
 }

 private void getNotifiSetting() {
 // TODO Auto-generated method stub
 
 if (prefs.getBoolean("isAutoStartEnabled", true)) {
 cbp5.setSummary("Start Notifications after Rebooting Phone - ON");
 } else {
 cbp5.setSummary("Start Notifications after Reboot - OFF (Not Recommended)");
 }
 
 if (prefs.getBoolean("NotiOnOff", true)) {
 cbp1.setSummary("Notification to remind you - ON");
 } else {
 cbp1.setSummary("Notification to remind you - OFF (Not Recommended)");
 }

 if (prefs.getBoolean("VibrateOnOff", true)) {
 cbp2.setSummary("Vibration On");
 } else {
 cbp2.setSummary("Vibration Off");
 }

 if (prefs.getBoolean("LightOnOff", true)) {
 cbp3.setSummary("LED On");
 } else {
 cbp3.setSummary("LED Off");
 }

 if (prefs.getBoolean("SoundOnOff", true)) {
 cbp4.setSummary("Sound On");
 } else {
 cbp4.setSummary("Sound Off");
 }
 }
 
 }
}

1.b) Create user_setting.xml file in the xml folder under res folder(if u don’t know how, please refer my previous blog on creating setting screen using preferencemanager) and copy the below code.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="Settings">

  <PreferenceCategory
     android:title="Notification Settings">

   <CheckBoxPreference
 android:defaultValue="true"
 android:key="isAutoStartEnabled"
 android:summary="Start Notifications after Rebooting Phone"
 android:title="Start on boot" />

 <CheckBoxPreference
 android:defaultValue="true"
 android:key="NotiOnOff"
 android:summary="Notification to remind you - ON"
 android:title="Notifications on/off" />

 <CheckBoxPreference
 android:defaultValue="true"
 android:dependency="NotiOnOff"
 android:key="VibrateOnOff"
 android:summary="Vibration On"
 android:title="Vibration on/off" />

 <CheckBoxPreference
 android:defaultValue="true"
 android:dependency="NotiOnOff"
 android:key="LightOnOff"
 android:summary="LED On"
 android:title="LED on/off" />

 <CheckBoxPreference
 android:defaultValue="true"
 android:dependency="NotiOnOff"
 android:key="SoundOnOff"
 android:summary="Sound On"
 android:title="Default App Sound on/off" />

  </PreferenceCategory>

</PreferenceScreen>

2) Create MyScheduledReceiver.java class and copy the below code.

import java.util.Calendar;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;

public class MyScheduledReceiver extends BroadcastReceiver {
	Boolean Noti_flag, Sound_flag, Vibrate_flag, Light_flag;

	@Override
	public void onReceive(Context context, Intent intent) {
		pref = PreferenceManager.getDefaultSharedPreferences(context);

		Noti_flag = SettingActivity.ReadBoolean(context, "NotiOnOff", true);
		Sound_flag = SettingActivity.ReadBoolean(context, "SoundOnOff", true);
		Vibrate_flag = SettingActivity.ReadBoolean(context, "VibrateOnOff", true);
		Light_flag = SettingActivity.ReadBoolean(context, "LightOnOff", true);

		if (Noti_flag) {

			PowerManager pm = (PowerManager) context
					.getSystemService(Context.POWER_SERVICE);
			PowerManager.WakeLock wl = pm.newWakeLock(
					PowerManager.PARTIAL_WAKE_LOCK, "");
			wl.acquire();

			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					context)
					.setSmallIcon(R.drawable.ic_launcher)
					.setAutoCancel(true)
					.addAction(
							android.R.drawable.ic_menu_save,
							"Ok, got it.",
							PendingIntent.getActivity(context, 12345,
									new Intent(context,
											MainActivity.class),
									PendingIntent.FLAG_ONE_SHOT))
					.addAction(
							android.R.drawable.ic_menu_close_clear_cancel,
							"Remind later",
							PendingIntent.getBroadcast(context, 12345,
									new Intent(context,
											NotificationCancel.class),
									PendingIntent.FLAG_ONE_SHOT))
					.setContentIntent(
							PendingIntent.getActivity(context, 12345,
									new Intent(context,
											MainActivity.class),
									PendingIntent.FLAG_ONE_SHOT))
					.setContentTitle("NotificaitionTesting")
					.setContentText("You got the notification from the service.");

			Notification notification = null;

			if (Build.VERSION.SDK_INT > 15) {
				notification = buildForJellyBean(builder);
			} else {
				notification = builder.build();
			}

			NotificationManager mNotificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);

			notification.flags |= Notification.FLAG_AUTO_CANCEL; // clear the
																	// notification

			if (Vibrate_flag) {
				notification.vibrate = (new long[] { 1000, 1000, 1000 });
			}
			if (Sound_flag) {
				notification.defaults |= Notification.DEFAULT_SOUND;

			}
			if (Light_flag) {

				notification.ledARGB = 0xff00ff00;
				notification.ledOnMS = 500;
				notification.ledOffMS = 500;
				notification.flags |= Notification.FLAG_SHOW_LIGHTS;
			}
			mNotificationManager.notify(123, notification);

			wl.release();
		}
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private Notification buildForJellyBean(NotificationCompat.Builder builder1) {
		// TODO Auto-generated method stub
		builder1.setPriority(Notification.PRIORITY_HIGH);
		return builder1.build();
	}

	public void SetAlarmR(Context context) {
		Calendar cal1 = Calendar.getInstance();
		cal1.set(Calendar.HOUR_OF_DAY, 10);
		cal1.set(Calendar.MINUTE, 10);
		cal1.set(Calendar.SECOND, 00);

		Calendar now = Calendar.getInstance();
		if (now.after(cal1))
			cal1.add(Calendar.DAY_OF_YEAR, 1);

		AlarmManager alarmManagerR = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent myIntentR1 = new Intent(context, MyScheduledReceiver.class);

		PendingIntent pendingIntentR1 = PendingIntent.getBroadcast(context, 1,
				myIntentR1, PendingIntent.FLAG_UPDATE_CURRENT);

		alarmManagerR.cancel(pendingIntentR1);

		if (Build.VERSION.SDK_INT > 19) {

			alarmManagerR.setInexactRepeating(AlarmManager.RTC_WAKEUP,
					cal1.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
					pendingIntentR1);

		} else {

			alarmManagerR.setRepeating(AlarmManager.RTC_WAKEUP,
					cal1.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
					pendingIntentR1);

		}
	}

	public void CancelAlarmR(Context context) {
		Intent myIntentR = new Intent(context, MyScheduledReceiver.class);

		PendingIntent pendingIntentR = PendingIntent.getBroadcast(context, 1,
				myIntentR, 0);

		AlarmManager alarmManagerR = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		alarmManagerR.cancel(pendingIntentR);

	}

}

3) Create NotificationCancel.java class and copy this code.

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NotificationCancel extends BroadcastReceiver{
	public static final int NOTIFICATION_ID = 123;

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

		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	    notificationManager.cancel(NotificationCancel.NOTIFICATION_ID);

	}

}

4) Create MyService.java class and copy this code.

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;

public class MyService extends Service
{
	Boolean Noti_flag;
	MyScheduledReceiver alarm = new MyScheduledReceiver();
    public void onCreate()
    {
       Noti_flag= SettingActivity.ReadBoolean(context, "NotiOnOff", true);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
{

	 	if(Noti_flag){
			alarm.SetAlarmR(MyService.this);
		}

     return START_STICKY;
}

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}

5) Create AutoStart.java class and copy paste this code.


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class AutoStart extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent arg1) {
Log.d("Autostart", "BOOT_COMPLETED broadcast received. Executing starter service.");
boolean isAutoStartEnabled = SettingActivity.ReadBoolean(context, "isAutoStartEnabled", true);

if(isAutoStartEnabled){
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
}
}
}
}

6) On your MainActivity.java class, copy paste this code.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button B1 = (Button)findViewById(R.id.button1);

		MyScheduledReceiver alarm = new MyScheduledReceiver();
		alarm.SetAlarmR(this);

		B1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intnt_setting = new Intent( MainActivity.this, SettingActivity.class);
				startActivity(intnt_setting);
			}
		});

	}
}

6.b) On your activity_main.xml file, copy paste this code.

<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.example.notificationtesting.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Settings" />

</RelativeLayout>

7) On your AndroidManifest.xml file, copy paste this code.

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

	<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
	<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".SettingActivity"
            android:label="@string/app_name" >

        </activity>

        <receiver android:name=".MyScheduledReceiver"/>
        <receiver android:name=".NotificationCancel" />

         <receiver
            android:name=".AutoStart"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

         <service android:name=".MyService"
                 android:enabled="true" />

    </application>

</manifest>

ScreenShot:

Screenshot_2014-09-30-17-48-10[1] Screenshot_2014-09-30-17-48-31[1] Screenshot_2014-09-30-17-50-42[1]

 

Congrats, you have sucessfully created Notification with AlarmManager using Service, AutoStart on Reboot and Setting screen in Android.
Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. William

Leave a Reply

Your email address will not be published. Required fields are marked *