Android based on broadcast event mechanism to achieve a simple regular reminder function code

  • 2020-09-16 07:46:32
  • OfStack

An example of Android based on broadcast event mechanism to achieve a simple regular reminder function code. To share for your reference, the details are as follows:

1.Android broadcast event mechanism

The broadcast event handling of Android is similar to normal event handling. The difference is that the latter is triggered by component behavior such as clicking a button, while the former transmits information by building an Intent object and using the sentBroadcast() method to initiate a system-level event broadcast. Receiving broadcast events is achieved by defining a class that inherits from Broadcast Receiver, overrides its onReceive() method, and responds to events in that method. Many standard Broadcast Action are defined in the Android system to respond to system broadcast events. For example: ACTION_TIME_CHANGED (triggered when time changes). However, we can also define Broadcast Receiver to receive broadcast events ourselves.

2. Realize simple regular reminder function

It mainly consists of three parts:

1) Timing - Broadcast by definition Activity
2) Receiving broadcast - by implementing BroadcastReceiver receiving broadcast
3) Remind - and remind users via Notification

Now let's concretely implement these three parts:

2.1 How to time the broadcast?

Now the mobile phone has the function of alarm clock, we can use the alarm function provided by the system to time, that is, broadcast. Specifically, AlarmManager can be used in Android development.

AlarmManager provides a system-level prompt service that allows you to schedule a certain service at a certain time.
The steps for using AlarmManager are as follows:

1) Obtain AlarmManager instance: AlarmManager object 1 is not directly instantiated, but obtained through Context.getSystemService (Context.es52EN_SERVIECE) method
2) Define an PendingIntent to broadcast.
3) Call the related methods of AlarmManager to set the timer, repeat reminders and other functions.

The detailed code is as follows (ES60en.java) :


package com.Reminder;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* trigger the Broadcast event and set the alarm
*/
public class ReminderSetting extends Activity {
  Button btnEnable;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /* create a button. When you click the button, the alarm clock is enabled */
    btnEnable=(Button)findViewById(R.id.btnEnable);
    btnEnable.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        setReminder(true);
      }
    });
  }
  /**
   * Set the alarm 
   * 
   * @param b whether enable the Alarm clock or not 
   */
  private void setReminder(boolean b) {
    // get the AlarmManager instance 
    AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);
    // create a PendingIntent that will perform a broadcast
    PendingIntent pi= PendingIntent.getBroadcast(ReminderSetting.this, 0, new Intent(this,MyReceiver.class), 0);
    if(b){
      // just use current time as the Alarm time. 
      Calendar c=Calendar.getInstance();
      // schedule an alarm
      am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
    }
    else{
      // cancel current alarm
      am.cancel(pi);
    }
  }
}

2.2 Receiving broadcast

Create a new class to inherit from BroadcastReceiver and implement the onReceive() method. When BroadcastReceiver receives the broadcast, it executes the OnReceive() method. So, we add the code to the OnReceive() method, and when we receive the broadcast, we jump to Activity, which displays the alert message. The specific code is as follows (ES74en. java) :


package com.Reminder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Receive the broadcast and start the activity that will show the alarm
*/
public class MyReceiver extends BroadcastReceiver {
  /**
   * called when the BroadcastReceiver is receiving an Intent broadcast.
   */
  @Override
  public void onReceive(Context context, Intent intent) {
    /* start another activity - MyAlarm to display the alarm */
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setClass(context, MyAlarm.class);
    context.startActivity(intent);
  }
}

Note: After creating BroadcastReceiver, you need to register in ES80en.xml:


<receiver android:name=".MyReceiver">  
    <intent-filter> 
    <action android:name= "com.Reminder.MyReceiver" /> 
  </intent-filter> 
</receiver>

2.3 Reminder function

Create a new Activity and in this Activity we will alert the user via the Notification object of Android. We will add the prompt sound,1 TextView to display the prompt content and 1 button to cancel the reminder.

The creation of Notification mainly includes:

1) The system level service NotificationManager is obtained through ES99en.getSystemService (NOTIFICATION_SERVICE).
2) Instantiate Notification object and set various properties we need, such as setting sound.
3) Call notify() method of NotificationManager to display Notification

The detailed code is as follows: ES111en.java


package com.Reminder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Display the alarm information 
*/
public class MyAlarm extends Activity {
  /**
   * An identifier for this notification unique within your application
   */
  public static final int NOTIFICATION_ID=1; 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.my_alarm);
    // create the instance of NotificationManager
    final NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // create the instance of Notification
    Notification n=new Notification();
    /* set the sound of the alarm. There are two way of setting the sound */
     // n.sound=Uri.parse("file:///sdcard/alarm.mp3");
    n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");
    // Post a notification to be shown in the status bar
    nm.notify(NOTIFICATION_ID, n);
    /* display some information */
    TextView tv=(TextView)findViewById(R.id.tvNotification);
    tv.setText("Hello, it's time to bla bla...");
    /* the button by which you can cancel the alarm */
    Button btnCancel=(Button)findViewById(R.id.btnCancel);
    btnCancel.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        nm.cancel(NOTIFICATION_ID);
        finish();
      }
    });
  }
}

I hope this article is helpful for Android programming.


Related articles: