OHS
OHS

Reputation: 195

Android app with daily notification

I'm making an android application.... and I've been trying to write the code for a daily notification set for a specific time of day. At first, I really thought this would be an easy task, almost every app in the play store has a timed notification. But after searching over and over again, all the methods and Youtube tutorials I've found failed to work for me. The problem probably lies in me, but I don't know what it is. All I need is a simple, elegant, easy to understand method (if there is such a thing). Any help would be greatly appreciated.

All the searching I've done has gotten me this far... but still without any luck:

This method is in my MainActivity class and is called only the first time the app is launched to set the alarm...

private void alarmMethod() {
    Intent myIntent = new Intent(this, NotifyService.class);
    AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
    pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

    // Set the alarm to start at approximately 2:00 p.m.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 14);

    // With setInexactRepeating(), you have to use one of the AlarmManager interval
    // constants--in this case, AlarmManager.INTERVAL_DAY.
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent);

    Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG)
            .show();

This is my NotifyService class:

package com.OHS.example;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class NotifyService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification mNotify = new NotificationCompat.Builder(this)
        .setContentTitle("Title")
        .setContentText("Hello World!")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(pIntent)
        .setSound(sound)
        .build();

    mNM.notify(1, mNotify);

}
}

Upvotes: 9

Views: 10998

Answers (3)

Trideep
Trideep

Reputation: 396

Try This Code. XML layout :

<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=".MainActivity" >

<TextView
    android:id="@+id/TextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Android Alarm Example:\n\rSetup an alarm event after 10 seconds from the current time. So just press Setup Alarm button and wait for 10 seconds. You can see a toast message when your alarm time will be reach." />

    <Button
        android:id="@+id/setAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:onClick="onClickSetAlarm"
        android:text="Set Alarm" />

Main Activity :

public class MainActivity extends Activity {

    //used for register alarm manager
    PendingIntent pendingIntent;
    //used to store running alarmmanager instance
    AlarmManager alarmManager;
    //Callback function for Alarmmanager event
    BroadcastReceiver mReceiver;

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

        //Register AlarmManager Broadcast receive.
        RegisterAlarmBroadcast();
    }
    public void onClickSetAlarm(View v)
    {
        //Get the current time and set alarm after 10 seconds from current time
        // so here we get 
        alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
    }
    private void RegisterAlarmBroadcast()
    {
          Log.i("Alarm Example:RegisterAlarmBroadcast()", "Going to register Intent.RegisterAlramBroadcast");

        //This is the call back function(BroadcastReceiver) which will be call when your 
        //alarm time will reached.
        mReceiver = new BroadcastReceiver()
        {
            private static final String TAG = "Alarm Example Receiver";
            @Override
            public void onReceive(Context context, Intent intent)
            {
                Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
            }
        };

        // register the alarm broadcast here
        registerReceiver(mReceiver, new IntentFilter("com.myalarm.alarmexample") );
        pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.myalarm.alarmexample"),0 );
        alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    }
    private void UnregisterAlarmBroadcast()
    {
        alarmManager.cancel(pendingIntent); 
        getBaseContext().unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }
}

I Hope this will help you, this worked for me. You can always calculate and set the time when you want to trigger the alarm. Happy Coding !!

Upvotes: 5

alijandro
alijandro

Reputation: 12147

You could use AlarmManager to schedule the daily notification. The document here provide a good explanation and example.

Setup the alarm.

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
    new Intent(this, MainService.class),
        PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar calendar = Calendar.getInstance();
    // set the triggered time to currentHour:08:00 for testing
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 8);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), 0, pendingIntent);

Service to handle the alarm.

public class MainService extends IntentService {

    public MainService() {
        super("mainservice");
    }

    public MainService(String name) {
        super(name);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.IntentService#onHandleIntent(android.content.Intent)
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        showNotification();
    }

    private void showNotification() {

        Uri soundUri = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("Alarm title")
                .setContentText("Alarm text")
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, new Intent(this,
                                SecondActivity.class),
                                PendingIntent.FLAG_UPDATE_CURRENT))
                .setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
                .build();
        NotificationManagerCompat.from(this).notify(0, notification);
    }

}

Upvotes: 2

Armin Ghoreishi
Armin Ghoreishi

Reputation: 58

as alijandro said if you want to have a daily notification in specific time you could use AlarmManager to schedule it and at that time show notification or if you want to get data from server, send a http request to retrieve your data and show notification to the user. But if you want to have push notification anytime you want, you could use GCM (Google Cloud Messaging). Look at this doc.

Upvotes: 0

Related Questions