android alarm clock timing task AlarmManager

     code directly

package com.example.alarmmanagerdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 *
 * @ClassName: AlarmReceiver  
 * @Description: This broadcast will be entered when the alarm time is up, and you can do some business at this time.
 * @author Dahai.zhou
 * @date June 2, 2016 13:38:52  
 *
 */
public class AlarmReceiver extends BroadcastReceiver {
	
	@Override
    public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "The alarm is ringing, we can do something~~", Toast.LENGTH_LONG).show();
    }

}

 

package com.example.alarmmanagerdemo;

import java.util.Calendar;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 *
 * @ClassName: MainActivity  
 * @Description: main interface
 * @author Dahai.zhou
 * @date June 2, 2016 13:39:38
 *
 */
public class MainActivity extends Activity {

	private static final String TAG = MainActivity.class.getSimpleName();
	
	private TimePicker mTimePicker;
	private Button mButton1;
	private Button mButton2;
	private Button mButtonCancel;

	private int mHour = -1;
	private int mMinute = -1;

	public static final long DAY = 1000L * 60 * 60 * 24;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);

		// get the current time
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		if(mHour == -1 && mMinute == -1) {
			mHour = calendar.get(Calendar.HOUR_OF_DAY);
			mMinute = calendar.get(Calendar.MINUTE);
		}

		mTimePicker = (TimePicker)findViewById(R.id.timePicker);
		mTimePicker.setCurrentHour(mHour);
		mTimePicker.setCurrentMinute(mMinute);
		mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
			
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
				
				mHour = hourOfDay;
				mMinute = minute;
			}
		});


		mButton1 = (Button)findViewById(R.id.normal_button);
		mButton1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
				PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

				// Execute this alarm after 10s
				Calendar calendar = Calendar.getInstance();
			 	calendar.setTimeInMillis(System.currentTimeMillis());
			 	calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
				calendar.add(Calendar.SECOND, 10);

				// register the alarm
				AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
				manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
				
				Toast.makeText(MainActivity.this, "Set simple alarm successfully!", Toast.LENGTH_LONG).show();
			}
		});
		
		mButton2 = (Button)findViewById(R.id.repeating_button);
		mButton2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
				PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

	            long firstTime = SystemClock.elapsedRealtime(); // The running time after booting up to now (including sleep time)
	            long systemTime = System.currentTimeMillis();

	            Calendar calendar = Calendar.getInstance();
			 	calendar.setTimeInMillis(System.currentTimeMillis());
			 	calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); // The time zone needs to be set here, otherwise there will be a time difference of 8 hours
			 	calendar.set(Calendar.MINUTE, mMinute);
			 	calendar.set(Calendar.HOUR_OF_DAY, mHour);
			 	calendar.set(Calendar.SECOND, 0);
			 	calendar.set(Calendar.MILLISECOND, 0);

			 	// selected daily time
			 	long selectTime = calendar.getTimeInMillis();	

			 	// If the current time is greater than the set time, then start from the set time of the next day
			 	if(systemTime > selectTime) {
			 		Toast.makeText(MainActivity.this, "The set time is less than the current time", Toast.LENGTH_SHORT).show();
			 		calendar.add(Calendar.DAY_OF_MONTH, 1);
			 		selectTime = calendar.getTimeInMillis();
			 	}

			 	// Calculate the time difference between the current time and the set time
			 	long time = selectTime - systemTime;
		 		firstTime += time;

	            // register the alarm
	            AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
	            manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
	                            firstTime, 10*1000, sender);

	            Log.i(TAG, "time ==== " + time + ", selectTime ===== "
            			+ selectTime + ", systemTime ==== " + systemTime + ", firstTime === " + firstTime);

	            Toast.makeText(MainActivity.this, "Set repeat alarm successfully! ", Toast.LENGTH_LONG).show();
			}
		});

		mButtonCancel = (Button)findViewById(R.id.cancel_button);
		mButtonCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
	            PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this,
	                    0, intent, 0);
	            
	            // cancel the alarm
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.cancel(sender);
			}
		});
	}

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

}

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmmanagerdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmmanagerdemo.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="com.example.alarmmanagerdemo.AlarmReceiver"
            android:process=":remote" >
        </receiver>
    </application>

</manifest>

 

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

    <TimePicker android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    <Button android:id="@+id/normal_button"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/timePicker"
        android:text="Set simple alarm" />

    <Button android:id="@+id/repeating_button"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/timePicker"
        android:layout_toRightOf="@id/normal_button"
        android:text="Set repeat alarm" />

    <Button android:id="@+id/cancel_button"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="-50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/repeating_button"
        android:layout_toRightOf="@id/normal_button"
        android:text="Cancel the alarm" />

</RelativeLayout>

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326890301&siteId=291194637