Step by step _ Android development course [33] _ AlarmManager (Global timer) and androidalarmmanager on the user interface

Source: Internet
Author: User

Step by step _ Android development course [33] _ AlarmManager (Global timer) and androidalarmmanager on the user interface

Focus on technology, enjoy life! -- QQ: 804212028.
Link: http://blog.csdn.net/y18334702058/article/details/44624305

  • Topic: AlarmManager (Global timer) on the user interface)
    -

Role of AlarmManager:

When the AlarmManager object is used with Intent, you can enable an Activity regularly, send a BroadCast, or enable a Service.

There are three common AlarmManager methods:

(1) set (int type, long startTime, PendingIntent pi );

This method is used to set a one-time alarm. The first parameter indicates the alarm type, the second parameter indicates the alarm execution time, and the third parameter indicates the alarm response action.

(2) setRepeating (int type, long startTime, long
IntervalTime, PendingIntent pi );

This method is used to set a repeated alarm. The first parameter indicates the alarm type, the second parameter indicates the first execution time of the alarm, and the third parameter indicates the interval between two executions of the alarm, the third parameter indicates the alarm response action.

(3) setInexactRepeating (int type, long startTime, long
IntervalTime, PendingIntent pi );

This method is also used to set repeated alarms, similar to the second method, but the interval between the two alarms is not fixed.

Parameters of the three methods are described as follows:

(1) int type: specifies the type of the alarm. Five values are commonly used: AlarmManager. ELAPSED_REALTIME,
AlarmManager. ELAPSED_REALTIME_WAKEUP, AlarmManager. RTC,
AlarmManager. RTC_WAKEUP and AlarmManager. POWER_OFF_WAKEUP.

AlarmManager. ELAPSED_REALTIME indicates that the alarm is unavailable when the mobile phone is sleeping. In this status, the relative time (relative to the start time of the system) is used for the alarm, and the status value is 3;

AlarmManager. ELAPSED_REALTIME_WAKEUP indicates that the alarm will wake up the system during sleep and execute the prompt function. In this status, the alarm will also use relative time, And the status value is 2;

AlarmManager. RTC indicates that the alarm is unavailable during sleep. In this status, the absolute time is used for the alarm, that is, the current system time. The status value is 1;

AlarmManager. RTC_WAKEUP indicates that the alarm will wake up the system during sleep and execute the prompt function. In this status, the alarm uses the absolute time and the status value is 0;

AlarmManager. POWER_OFF_WAKEUP indicates that the alarm notification function can be performed normally when the phone is shut down. Therefore, it is one of the five most frequently used states. In this status, the alarm notification uses absolute time and the status value is 4; however, this status seems to be affected by the SDK version, which is not supported by some versions;

(2) long startTime:
The first execution time of the alarm, in milliseconds. The time can be customized, but the current time is generally used. Note that this attribute is closely related to the first attribute (type ).
The corresponding alert clock uses relative time (ELAPSED_REALTIME and ELAPSED_REALTIME_WAKEUP). Therefore, this attribute must use relative time (relative
For example, the current time is expressed as SystemClock. elapsedRealtime (). If the first parameter corresponds to an absolute time
(RTC, RTC_WAKEUP, POWER_OFF_WAKEUP), this attribute requires absolute time, for example, the current time indicates
Is: System. currentTimeMillis ().

(3) long intervalTime: For the last two methods, this attribute exists, indicating the interval between the two alarms, in milliseconds.

(4) PendingIntent pi:
It is bound to the execution action of the alarm, such as sending a broadcast and giving a prompt. PendingIntent is the encapsulation class of Intent. It should be noted that, if the alarm is triggered by starting the service
To obtain the PendingIntent object, use Pending. getService (Context c, int I, Intent
Intent, int j) method; if the alarm is triggered by broadcasting, the PendingIntent object should be obtained using
PendingIntent. getBroadcast (Context c, int I, Intent intent, int
J) method. If you use the Activity method to implement the alarm notification, you should use the PendingIntent object.
PendingIntent. getActivity (Context c, int I, Intent intent, int
J) method. If these three methods are used incorrectly, although no error is reported, the alarm is not displayed.

AlarmManager global timer (Instance ):

Implementation Effect: AlarmManager regularly enables an Activity, sends a BroadCast and starts a Service.
AndroidManifest. xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.yfz"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="7" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".MainActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver            android:name="ActionBroadCast">        </receiver>        <service android:name="ActionService"></service>        <activity android:name="ActionActivity"></activity>    </application></manifest>

Main. xml:

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <Button android: id = "@ + id/id_btn1" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "BroadCast"/> <Button android: id = "@ + id/id_btn2" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Service"/> <Button android: id = "@ + id/id_btn3" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Activity"/> </LinearLayout>

MainActivity. java:

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;public class MainActivity extends Activity {     AlarmManager am ;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        am = (AlarmManager)getSystemService(ALARM_SERVICE);        Button btn1 = (Button)findViewById(R.id.id_btn1);        Button btn2 = (Button)findViewById(R.id.id_btn2);        Button btn3 = (Button)findViewById(R.id.id_btn3);        btn1.setOnClickListener(onclick);        btn2.setOnClickListener(onclick);        btn3.setOnClickListener(onclick);    }    OnClickListener onclick = new OnClickListener() {        @Override        public void onClick(View v) {            long now = System.currentTimeMillis();            PendingIntent pi = null;            switch (v.getId()) {                case R.id.id_btn1:                    pi = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(MainActivity.this, ActionBroadCast.class), Intent.FLAG_ACTIVITY_NEW_TASK);                    break;                case R.id.id_btn2:                    pi = PendingIntent.getService(MainActivity.this, 0, new Intent(MainActivity.this, ActionService.class), Intent.FLAG_ACTIVITY_NEW_TASK);                    break;                case R.id.id_btn3:                    pi = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, ActionActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK);                    break;                default:                    break;            }            am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi);        }    };}

ActionActivity. java:

import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.widget.Button;public class ActionActivity extends Activity {    private static int num = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        Log.e("ActionActivity", "Activity New Message !" + num++);    }   }   

ActionBroadCast. java:

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class ActionBroadCast extends BroadcastReceiver {    private static int num = 0;    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        Log.e("ActionBroadCast", "New Message !" + num++);    }}

ActionService. java:

import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class ActionService extends Service {    private static int num = 0;    @Override    public IBinder onBind(Intent arg0) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onStart(Intent intent, int startId) {        // TODO Auto-generated method stub        super.onStart(intent, startId);        Log.e("ActionService", "Service New Message !" + num++);    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // TODO Auto-generated method stub        Log.e("ActionService", "----------");        return super.onStartCommand(intent, flags, startId);    }}

Focus on technology, enjoy life! -- QQ: 804212028.
Link: http://blog.csdn.net/y18334702058/article/details/44624305

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.