Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

}
}
like image 460
OHS Avatar asked Mar 15 '15 07:03

OHS


2 Answers

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 !!

like image 175
Trideep Avatar answered Sep 21 '22 18:09

Trideep


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);
    }

}
like image 22
alijandro Avatar answered Sep 20 '22 18:09

alijandro