我想在我的项目中实现计划功能。所以我用Google搜索了一个警报管理器程序,但是找不到任何示例。
有人可以通过基本的警报管理器程序帮助我吗?
我想在我的项目中实现计划功能。所以我用Google搜索了一个警报管理器程序,但是找不到任何示例。
有人可以通过基本的警报管理器程序帮助我吗?
Answers:
这是工作代码。它每10分钟唤醒一次CPU,直到手机关闭。
添加到Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...
您班上的代码:
package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
从服务设置警报:
package yourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
如果要设置在电话启动时重复发出警报:
向Manifest.xml添加权限和服务:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>
并创建一个新类:
package yourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}
am.setInexactRepeating(...)
因此不会因为服务而不必要地唤醒电话。其他程序员应注意这一事实。2.不是创建一个新的Alarm
在AutoStart
在收到RECEIVE_BOOT_COMPLETED
意向,可能更有意义,开始YourService
从AutoStart
,如下所示:stackoverflow.com/a/5439320/198348
WakefulBroadcastReceiver
从Android O
我尝试了来自XXX的解决方案,尽管该解决方案最初确实有效,但在某个时候它停止了工作。该onReceive
从来没有得到再次调用。我花了几个小时试图弄清楚它可能是什么。我意识到Intent
,无论出于什么神秘原因,都不再被称为。为了解决这个问题,我发现您确实需要为清单中的接收者指定一个操作。例:
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="mypackage.START_ALARM" >
</action>
</intent-filter>
</receiver>
请注意名称".Alarm"
与句点。在XXX的setAlarm
方法中,创建Intent
如下:
Intent i = new Intent("mypackage.START_ALARM");
该START_ALARM
消息可以是您想要的任何内容。我只是给这个名字起示范作用。
我没有在清单中定义没有指定动作的意图过滤器的接收者。按照XXX指定的方式创建它们似乎是虚假的。通过指定动作名称,Android将被迫BroadcastReceiver
使用与该动作对应的类创建的实例。如果您依赖上下文,请注意,Android有几个不同的对象,它们全部称为上下文,并且可能不会导致您BroadcastReceiver
创建它。强迫Android仅使用操作消息创建类的实例要比依靠某些可能永远无法工作的虚假上下文好得多。
PendingIntent.getBroadcast
文档,For security reasons, the Intent you supply here should almost always be an explicit intent, that is specify an explicit component to be delivered to through Intent.setClass
。
android:exported="true"
需要为它工作?
这是一个相当独立的示例。5秒后,按钮变为红色。
public void SetAlarm()
{
final Button button = buttons[2]; // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive( Context context, Intent _ )
{
button.setBackgroundColor( Color.RED );
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}
请记住,即使您的应用程序未运行,AlarmManager也会触发。如果调用此功能并按“主页”按钮,请等待5秒钟,然后再返回到您的应用程序,该按钮将变为红色。
我不知道如果您的应用程序根本不在内存中,您将得到什么样的行为,因此请注意尝试保持哪种状态。
RTC_WAKEUP
代替ELAPSED_REALTIME_WAKEUP
)似乎并不会触发应用程序中的接收器,该应用程序显然已被系统卸载以节省功耗,尽管在将主屏幕显示到前台后不久它确实可以工作。
MainActivity.java
package com.example.alarmexample;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert();
} public void startAlert() {
int timeInSec = 2;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmexample" >
<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.example.alarmexample.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>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
AlarmManager
与IntentService
我认为最好的使用模式AlarmManager
是与的协作IntentService
。由IntentService
触发AlarmManager
,它通过接收意图处理所需的操作。这种结构不会像使用那样对性能产生影响BroadcastReceiver
。我已经为这个想法开发了一个示例代码科特林 在这里可用:
MyAlarmManager.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
object MyAlarmManager {
private var pendingIntent: PendingIntent? = null
fun setAlarm(context: Context, alarmTime: Long, message: String) {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MyIntentService::class.java)
intent.action = MyIntentService.ACTION_SEND_TEST_MESSAGE
intent.putExtra(MyIntentService.EXTRA_MESSAGE, message)
pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
}
fun cancelAlarm(context: Context) {
pendingIntent?.let {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(it)
}
}
}
MyIntentService.kt
import android.app.IntentService
import android.content.Intent
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.apply {
when (intent.action) {
ACTION_SEND_TEST_MESSAGE -> {
val message = getStringExtra(EXTRA_MESSAGE)
println(message)
}
}
}
}
companion object {
const val ACTION_SEND_TEST_MESSAGE = "ACTION_SEND_TEST_MESSAGE"
const val EXTRA_MESSAGE = "EXTRA_MESSAGE"
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aminography.alarm">
<application
... >
<service
android:name="path.to.MyIntentService"
android:enabled="true"
android:stopWithTask="false" />
</application>
</manifest>
用法:
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, 10)
MyAlarmManager.setAlarm(applicationContext, calendar.timeInMillis, "Test Message!")
如果要取消预定的警报,请尝试以下操作:
MyAlarmManager.cancelAlarm(applicationContext)
此代码将帮助您发出重复警报。重复时间可以由您设置。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:background="#000000"
android:paddingTop="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<EditText
android:id="@+id/ethr"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Hr"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etmin"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Min"
android:singleLine="true" />
<EditText
android:id="@+id/etsec"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Sec"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp">
<Button
android:id="@+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
int hr = 0;
int min = 0;
int sec = 0;
int result = 1;
AlarmManager alarmManager;
PendingIntent pendingIntent;
BroadcastReceiver mReceiver;
EditText ethr;
EditText etmin;
EditText etsec;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ethr = (EditText) findViewById(R.id.ethr);
etmin = (EditText) findViewById(R.id.etmin);
etsec = (EditText) findViewById(R.id.etsec);
RegisterAlarmBroadcast();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public void onClickSetAlarm(View v) {
String shr = ethr.getText().toString();
String smin = etmin.getText().toString();
String ssec = etsec.getText().toString();
if(shr.equals(""))
hr = 0;
else {
hr = Integer.parseInt(ethr.getText().toString());
hr=hr*60*60*1000;
}
if(smin.equals(""))
min = 0;
else {
min = Integer.parseInt(etmin.getText().toString());
min = min*60*1000;
}
if(ssec.equals(""))
sec = 0;
else {
sec = Integer.parseInt(etsec.getText().toString());
sec = sec * 1000;
}
result = hr+min+sec;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
}
private void RegisterAlarmBroadcast() {
mReceiver = new BroadcastReceiver() {
// private static final String TAG = "Alarm Example Receiver";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
registerReceiver(mReceiver, new IntentFilter("sample"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
}
private void UnregisterAlarmBroadcast() {
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
}
如果您只需要一次警报,请更换
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
与
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );
我已经实现了自己的实现,以尽可能简单的方式做到这一点。
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public void stop() {
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
backgroundTaskListener.perform(context, intent);
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
唯一的下一步,实施它。
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import ...AbstractSystemServiceTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Daniel on 28/08/2016.
*/
public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {
private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;
public UpdateInfoSystemServiceTask(Context context) {
super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {
@Override
public void perform(Context context, Intent intent) {
Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");
//DO HERE WHATEVER YOU WANT...
}
});
Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
}
}
我喜欢使用此实现,但是另一种可能的好方法是,不要将AbstractSystemServiceTask
类抽象化,而是通过Builder构建它。
希望对您有帮助。
UPDATED
改进,允许BackgroundTaskListener
在同一位置上有多个BroadCastReceiver
。
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
private final Set<BackgroundTaskListener> backgroundTaskListenerSet;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.backgroundTaskListenerSet = new HashSet<>();
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.add(backgroundTaskListener);
}
public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.remove(backgroundTaskListener);
}
public void stop() {
this.backgroundTaskListenerSet.clear();
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver() {
return new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {
backgroundTaskListener.perform(context, intent);
}
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
警报管理器:
添加到XML布局(*在主活动中创建时初始化这些视图)
<TimePicker
android:id="@+id/timepicker"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"></TimePicker>
<Button
android:id="@+id/btn_start"
android:text="start Alarm"
android:onClick="start_alarm_event"
android:layout_width="match_parent"
android:layout_height="52dp" />
添加到清单(内部应用程序标记和&外部活动)
<receiver android:name=".AlarmBroadcastManager"
android:enabled="true"
android:exported="true"/>
创建AlarmBroadcastManager类(继承自BroadcastReceiver)
public class AlarmBroadcastManager extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
在主要活动中(添加以下功能):
@RequiresApi(api = Build.VERSION_CODES.M)
public void start_alarm_event(View view){
Calendar calendar=Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
setAlarm(calendar.getTimeInMillis());
}
public void setAlarm(long timeInMillis){
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmBroadcastManager.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();
}
这是使用Kotlin的Alarm Manager的示例:
class MainActivity : AppCompatActivity() {
val editText: EditText by bindView(R.id.edit_text)
val timePicker: TimePicker by bindView(R.id.time_picker)
val buttonSet: Button by bindView(R.id.button_set)
val buttonCancel: Button by bindView(R.id.button_cancel)
val relativeLayout: RelativeLayout by bindView(R.id.activity_main)
var notificationId = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
timePicker.setIs24HourView(true)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
buttonSet.setOnClickListener {
if (editText.text.isBlank()) {
Toast.makeText(applicationContext, "Title is Required!!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
alarmManager.set(
AlarmManager.RTC_WAKEUP,
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, timePicker.hour)
set(Calendar.MINUTE, timePicker.minute)
set(Calendar.SECOND, 0)
}.timeInMillis,
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, AlarmBroadcastReceiver::class.java).apply {
putExtra("notificationId", ++notificationId)
putExtra("reminder", editText.text)
},
PendingIntent.FLAG_CANCEL_CURRENT
)
)
Toast.makeText(applicationContext, "SET!! ${editText.text}", Toast.LENGTH_SHORT).show()
reset()
}
buttonCancel.setOnClickListener {
alarmManager.cancel(
PendingIntent.getBroadcast(
applicationContext, 0, Intent(applicationContext, AlarmBroadcastReceiver::class.java), 0))
Toast.makeText(applicationContext, "CANCEL!!", Toast.LENGTH_SHORT).show()
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(relativeLayout.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
relativeLayout.requestFocus()
return super.onTouchEvent(event)
}
override fun onResume() {
super.onResume()
reset()
}
private fun reset() {
timePicker.apply {
val now = Calendar.getInstance()
hour = now.get(Calendar.HOUR_OF_DAY)
minute = now.get(Calendar.MINUTE)
}
editText.setText("")
}
}