美文网首页Android 成长笔记
AlarmManager 设置和取消定时器 实例

AlarmManager 设置和取消定时器 实例

作者: 赵者也 | 来源:发表于2017-11-14 20:02 被阅读73次

    使用 AlarmManager 设置定时器的方法如下:

            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                    new Intent(ACTION_TIMEOUT), PendingIntent.FLAG_UPDATE_CURRENT);
    
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
            am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60 * 1000, // 60s later
                    pendingIntent);
    

    使用 AlarmManager 取消定时器的方法如下:

            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                    new Intent(ACTION_TIMEOUT), PendingIntent.FLAG_UPDATE_CURRENT);
    
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
            try {
                am.cancel(pendingIntent);
                Log.d(TAG, "Alarm is Canceled.");
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "Alarm is not Canceled: " + e.toString());
            }
    

    下面是完整的测试程序的代码的 java 部分

    package com.toby.test_application;
    
    import android.app.Activity;
    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 android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
        private static final String TAG = "Test_MainActivity";
        private static final String ACTION_TIMEOUT = "com.toby.action.TIMEOUT";
    
        private static IntentFilter s_intentFilter;
    
        static {
            s_intentFilter = new IntentFilter();
            s_intentFilter.addAction(ACTION_TIMEOUT);
        }
    
        private final BroadcastReceiver m_testReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();
    
                if (action.equals(ACTION_TIMEOUT)) {
                    Log.d(TAG, "ACTION_TIMEOUT is Received");
                    Toast.makeText(MainActivity.this,
                            TAG + " " + ACTION_TIMEOUT, Toast.LENGTH_SHORT).show();
                }
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            registerReceiver(m_testReceiver, s_intentFilter);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(m_testReceiver);
        }
    
        public void startAlarm(View view) {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                    new Intent(ACTION_TIMEOUT), PendingIntent.FLAG_UPDATE_CURRENT);
    
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
            am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60 * 1000, // 60s later
                    pendingIntent);
    
            Log.d(TAG, "Alarm is Set.");
        }
    
        public void stopAlarm(View view) {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                    new Intent(ACTION_TIMEOUT), PendingIntent.FLAG_UPDATE_CURRENT);
    
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
            try {
                am.cancel(pendingIntent);
                Log.d(TAG, "Alarm is Canceled.");
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "Alarm is not Canceled: " + e.toString());
            }
        }
    }
    

    然后是布局文件 activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <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"
        tools:context="com.toby.test_application.MainActivity">
    
        <Button
            android:id="@+id/startButton"
            android:text="@string/start_alarm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="147dp"
            tools:layout_editor_absoluteY="131dp"
            android:layout_alignParentTop="true"
            android:layout_alignStart="@+id/stopButton"
            android:layout_marginTop="83dp"
            android:onClick="startAlarm"
            />
    
        <Button
            android:id="@+id/stopButton"
            android:text="@string/stop_alarm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="148dp"
            tools:layout_editor_absoluteY="211dp"
            android:layout_marginTop="22dp"
            android:layout_below="@+id/startButton"
            android:layout_centerHorizontal="true"
            android:onClick="stopAlarm"
            />
    </RelativeLayout>
    

    String.xml 文件的代码:

    <resources>
        <string name="app_name">Test_Application</string>
    
        <string name="start_alarm">Start Alarm</string>
        <string name="stop_alarm">Stop Alarm</string>
    </resources>
    

    程序的运行效果:

    运行效果

    相关文章

      网友评论

      • c82bf09cf357:好浅,总觉得一点价值都没有。
        赵者也:@加菲糖 嗯,那会儿也是初学,记下来备忘一下

      本文标题:AlarmManager 设置和取消定时器 实例

      本文链接:https://www.haomeiwen.com/subject/xoafvxtx.html