Android中AlarmManager使用示例

现在普遍的手机都会有一个闹钟的功能,如果使用Android来实现一个闹钟可以使用AtarmManager来实现。AtarmManager提供了一种系统级的提示服务,允许你安排在将来的某个时间执行一个服务。AlarmManager对象一般不直接实例化,而是通过Context.getsystemservice(Context.ALARM_SERVICE)方法获得。

下面是我们运用之前用到的TimePickerDialog结合AlarmManager,实现一个可以设定任意时间而且可以重复的闹钟,演示效果如下(大概每晚23:48会有闹钟通知):

Android中AlarmManager使用示例

layout中activity_main.xml布局文件代码:

1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:id="@+id/activity_main" 6 android:layout_width="match_parent" 7 android:layout_height="match_parent" 8 android:orientation="vertical" 9 tools:context="com.example.administrator.alarmdemo.MainActivity"> 10 <TextView 11 android:id="@+id/time_tv" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:hint="请设置闹铃时间" 15 android:clickable="true" 16 android:onClick="setTime" 17 android:gravity="center"/> 18 <TextView 19 android:id="@+id/time_tv2" 20 android:layout_width="match_parent" 21 android:layout_height="wrap_content" 22 android:hint="请设置响铃间隔时间" 23 android:clickable="true" 24 android:onClick="setIntervalTime" 25 android:gravity="center"/> 26 <Button 27 android:layout_width="match_parent" 28 android:layout_height="wrap_content" 29 android:onClick="open" 30 android:text="开启闹钟"/> 31 <Button 32 android:layout_width="match_parent" 33 android:layout_height="wrap_content" 34 android:onClick="stop" 35 android:text="结束闹钟"/> 36 </LinearLayout>

AndroidMainfest.xml配置文件(添加自定义重复闹铃receiver):

1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.administrator.alarmdemo"> 4 <application 5 android:allowBackup="true" 6 android:icon="@mipmap/ic_launcher" 7 android:label="@string/app_name" 8 android:supportsRtl="true" 9 android:theme="@style/AppTheme"> 10 <activity android:name=".MainActivity"> 11 <intent-filter> 12 <action android:name="android.intent.action.MAIN" /> 13 14 <category android:name="android.intent.category.LAUNCHER" /> 15 </intent-filter> 16 </activity> 17 <receiver 18 android:name=".RepeatAlarmReceiver" 19 android:enabled="true" 20 android:exported="true"> 21 <intent-filter> 22 <action android:name="repeatAlarm" /> 23 </intent-filter> 24 </receiver> 25 <activity android:name=".Main2Activity"></activity> 26 </application> 27 28 </manifest>

RepeatAlarmReceiver.java广播接收文件:

1 import android.content.BroadcastReceiver; 2 import android.content.Context; 3 import android.content.Intent; 4 import android.widget.Toast; 5 6 public class RepeatAlarmReceiver extends BroadcastReceiver { 7 public RepeatAlarmReceiver() { 8 } 9 @Override 10 public void onReceive(Context context, Intent intent) { 11 Toast.makeText(context, "重复闹钟", Toast.LENGTH_SHORT).show(); 12 } 13 }

MainActivity.java代码实现:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/2ba4e18d49c5c06cbeb5b3ca820829d1.html