Android初級教程啟動定時器詳解

來源:互聯網
上載者:User

標籤:

本案例知識是:後台執行定時任務。

Alarm機制:

一、建立LongRunningService類

package com.example.servicebestpractice;import java.util.Date;import android.app.AlarmManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;public class LongRunningService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {new Thread(new Runnable() {@Overridepublic void run() {// 列印日誌類比耗時操作。System.out.println("服務啟動時間:" + new Date().toString());}}).start();AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);int times = 1000 * 60;// 設定相隔多久啟動一次廣播,我設定為1分鐘啟動一次服務,去執行定時任務(雖然我寫的是列印一條日誌,看起來很無趣)long triggerAtime = SystemClock.elapsedRealtime() + times;// 設定觸發時間點Intent i = new Intent(this, AlarmReceiver.class);// 服務啟動廣播的intent意圖PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);// 封裝pendingIntent,啟動廣播接收者意圖manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtime,pendingIntent);// 設定精確定時時間,定時到了觸發,廣播啟動。return super.onStartCommand(intent, flags, startId);}}

二、建立要接收上述要啟動的廣播。

package com.example.servicebestpractice;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class AlarmReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {//服務類時間到啟動廣播這行這個方法Intent intent2 = new Intent(context, LongRunningService.class);context.startService(intent2);//啟動廣播做啟動服務作業,服務又一次啟動。//由於服務不再前台,因此不需要設定addFlags();方法。因為服務不再藉助任務棧去建立了。}}

三、我們要有一個啟動服務的入口,那就選擇在主活動作為入口:

package com.example.servicebestpractice;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //主活動要首先有一次啟動服務的操作        Intent intent3 = new Intent(this, LongRunningService.class);        startService(intent3);//啟動服務    }    }

四、廣播、活動、服務三大組件記得去資訊清單檔配置一下:

<activity            android:name="com.example.servicebestpractice.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>        <service android:name="com.example.servicebestpractice.LongRunningService" >        </service>        <receiver android:name="com.example.servicebestpractice.AlarmReceiver" >        </receiver>

寫完這篇部落格後,看了一下我的log後台輸出如下:

每隔一分鐘,定時任務完成,啟動一次服務。



Android初級教程啟動定時器詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.