创建定时任务

Android中的定时任务一般有两种实现方式,一种是使用Java API里提供的Timer类,一种是使用Android的Alarm机制。这两种方式在多数情况下都能实现类似的效果,但是Timer有一个明显的短板,它并不太适用于那些需要长期在后台运行的定时任务。我们都知道,为了能让电池更加耐用 ,每种手机都会有自己的休眠策略,Android手机就会在长时间不操作的情况下自动让CPU进入睡眠状态,这就有可能导致Timer中的定时任务无法正常运行。而Alarm则具有唤醒CPU的功能,它可以保证在大多数情况下需要执行定时任务的时候CPU都能正常工作。

创建一个LongRunningService的类,并继承Service

package com.example.hzx.longrunningservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by hzx on 2018/11/7.
 */

public class LongRunningService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand(Intent intent,int flags,int startId){
        Log.d("123","LongRunningService onStartCommand");
        AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
        int anHour = 5*1000;
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this,LongRunningService.class);
        PendingIntent pi = PendingIntent.getService(this,0,i,0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        Toast.makeText(this,"你很帅!!!",Toast.LENGTH_SHORT).show();;

        return super.onStartCommand(intent,flags,startId);
    }
}


MainActivity

package com.example.hzx.longrunningservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("123","MainActivity onCreate");
        Intent intent = new Intent(this,LongRunningService.class);
        this.startService(intent);

    }
}


注意:
1、 需要在AndroidMainifest.xml 注册服务
<service android:name=".LongRunningService"/>


image.png

效果:
每5秒会启动服务,服务启动是提示"你很帅!!!"

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,473评论 2 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,185评论 25 708
  • Android中的定时任务实现方式有两种,一种是Java API 里提供的Timer类,一种是Android的Al...
    gogoingmonkey阅读 467评论 0 0
  • 创建定时任务解决打盹问题,但是会在后台不断唤醒cpu,可能对设备续航有一些影响。 Alarm模式(警报模式):An...
    WangSins阅读 764评论 0 0
  • 晚上十点,我拖着疲惫的身体回到家里,客厅里一片漆黑,我左手顺势打开电灯开关,右手放下手上的公文包,客厅桌上是一片狼...
    冬日晨殇阅读 357评论 0 0

友情链接更多精彩内容