安卓 开启service每分钟执行一次任务 模拟定时 或者定时任务

再开始之前我们还是先介绍下service吧:此处用的是IntentService,至于和常规的service有什么区别呢?

有了Service为什么还要有个IntentService呢?

原因如下:

1)Service默认运行在主线程中,IntentService运行在一个新的线程中

2)Service需要主动调用stopSelf()或stopService()服务才可以停止,IntentService运行完后自动停止

使用IntentService需要注意2点:

1)构造函数中一定要调用父类的有参构造函数

2)需要耗时处理的事情放在onHandleIntent(Intent intent) 函数中
 

代码部分:此处实现的功能是一个在后台每分钟执行一次任务,时间可以修改,可以替代闹钟

MainActivity:


public class MainActivity extends Activity {


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


        //开启service  执行定时闹钟
        Intent intent=new Intent(MainActivity.this, My_Service.class);
        startService(intent);
    
    }
}
My_Service:
package youli.com.example.administrator.ysapp_demo.fragment.YAOXIANG.naozhong;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import youli.com.example.administrator.ysapp_demo.Utils.SharedPreferencesUtils;

/**
 * Created by Administrator on 2020/2/11.
 */

public class My_Service extends IntentService {

    Dialog dialog;

    private ArrayList<Ringtone> listRingTone = new ArrayList<>();

    private RingtoneManager ringtoneManager = null;

    private String ls;
    private int ckig;


    private List<String> time;
    private List<String> Shared_switch;

    private static final String TAG = My_Service.class.getSimpleName();
 
    //super(TAG); 此处要给一个值 不然会报错
    public My_Service() {
        super(TAG);
    }

    private int OPEN = 10000;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == OPEN) {

                String values = String.valueOf(msg.obj);
                initview(values);  //开启提示音 与对话框
            }
        }
    };

    Map<String,List<String>> KV=null;

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {


         //开启一个while循环,给值为true无线循环

        while (true) {
            try {
               //此处睡眠代表多久执行一次 一秒是1000
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

             //此处是关键代码 
            String day_key = My_Service_Utils.getCalendar_day();

            if(KV==null||!KV.containsKey(day_key))
            {
                KV = new HashMap<>();
                KV.put(day_key, new ArrayList<String>() );
            }

            // 铃声管理器
            My_Service_Utils.getRingtoneManager(this, ringtoneManager, listRingTone);

            Shared_switch = new ArrayList<>();  //存放定时是否已开启
            time = new ArrayList<>();  //存放时间

            Shared_switch.clear();
            Shared_switch = My_Service_Utils.get_Shared_switch();
            time.clear();
            time = My_Service_Utils.get_time();

             //循环闹钟开启按钮是否打开  
            for (int i = 0; i < Shared_switch.size(); i++) {
                      
                      // 如果值等于 "TRUE"代表闹钟已开启
                if (TextUtils.equals(Shared_switch.get(i), "TRUE")) {

                     //获取定时的时间
                    String show_time = time.get(i) ;  

                    Log.e("QQQ",show_time+"---"+My_Service_Utils.getCalendar()+"---"+i);
                       
 
                          //如多定时的时间show_time包含当前My_Service_Utils.getCalendar()系统的时间就往下执行
                    if (show_time.contains(My_Service_Utils.getCalendar())) {
                       
                        //此处控制一分钟执行一次
                        if(KV.get(day_key).contains(show_time ))
                        {
                            continue;
                        }
                        else
                        {
                            KV.get(day_key).add(show_time);
                        }


                        String open = String.valueOf(i + 1);  //这里的值代对应要开关的灯

                        My_Service_Utils.getOpen(this, open);//开灯

                        Message msg = new Message();
                        msg.obj = open;
                        msg.what = OPEN;
                        handler.sendMessage(msg);
                    }
                }
            }
        }
    }


    private void initview(final String open) {

        //获取需要播放的铃声
        ls = SharedPreferencesUtils.getString("LS");

        if (!TextUtils.equals(ls, "")) {
            ckig = Integer.parseInt(ls);
        } else {
            ckig = 0;
        }

        listRingTone.get(ckig).play();

        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
        builder.setMessage("该吃药了哦!");

        builder.setPositiveButton("已完成", new DialogInterface.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(DialogInterface dialog, int which) {

                listRingTone.get(ckig).stop();  //关闭音乐

                My_Service_Utils.getClose(getApplicationContext(), open);          //关灯

            }
        });
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();

    }


}
String day_key = My_Service_Utils.getCalendar_day(); 获取年月日,以这个作为map集合的key
String show_time = time.get(i) ;//定时的时间

应为睡眠时间设置的是10秒执行一次,当到达定时的时间先回判断 KV.get(day_key).contains(show_time )是否包含当前时间,包含continue退出,否则把当前时间添加到 KV.get(day_key).add(show_time);并执行余下代码操作

if(KV.get(day_key).contains(show_time ))
{
    continue;
}
else
{
    KV.get(day_key).add(show_time);
}

上面所用到的工具类:
package youli.com.example.administrator.ysapp_demo.fragment.YAOXIANG.naozhong;

import android.content.Context;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.support.annotation.RequiresApi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import youli.com.example.administrator.ysapp_demo.Utils.SharedPreferencesUtils;
import youli.com.example.administrator.ysapp_demo.chuankou.week_RQ;
import youli.com.example.administrator.ysapp_demo.fragment.FragmentYaoXiang;
import youli.com.example.administrator.ysapp_demo.fragment.YAOXIANG.timeutils;

/**
 * Created by Administrator on 2020/3/3.
 */

public class My_Service_Utils {


    public static void getRingtoneManager(Context context, RingtoneManager ringtoneManager, ArrayList<Ringtone> listRingTone) {
        if (ringtoneManager == null) {
            ringtoneManager = new RingtoneManager(context); // 铃声管理器
            Cursor cursor = ringtoneManager.getCursor(); //获取铃声表,根据表名取值
            int count = cursor.getCount(); //获取铃声列表数量
            for (int i = 0; i < count; i++) {
                listRingTone.add(ringtoneManager.getRingtone(i));
            }
        }
    }


    public static void getOpen(Context context, String values) {

        //开灯
        switch (Integer.valueOf(values)) {
            case 1:
                week_RQ.send_Serial(context, (byte) 0x01);
                break;
            case 2:
                week_RQ.send_Serial(context, (byte) 0x02);
                break;
            case 3:
                week_RQ.send_Serial(context, (byte) 0x04);
                break;
            case 4:
                week_RQ.send_Serial(context, (byte) 0x08);
                break;
            case 5:
                week_RQ.send_Serial(context, (byte) 0x10);
                break;
            case 6:
                week_RQ.send_Serial(context, (byte) 0x20);
                break;
            case 7:
                week_RQ.send_Serial(context, (byte) 0x40);
                break;
            case 8:
                week_RQ.send_Serial(context, (byte) 0x01);
                break;
            case 9:
                week_RQ.send_Serial(context, (byte) 0x02);
                break;
            case 10:
                week_RQ.send_Serial(context, (byte) 0x04);
                break;
            case 11:
                week_RQ.send_Serial(context, (byte) 0x08);
                break;
            case 12:
                week_RQ.send_Serial(context, (byte) 0x10);
                break;
            case 13:
                week_RQ.send_Serial(context, (byte) 0x20);
                break;
            case 14:
                week_RQ.send_Serial(context, (byte) 0x40);
                break;

        }
    }

    //关灯
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void getClose(final Context context, String values) {
        //关灯
        switch (Integer.valueOf(values)) {
            case 1:

                week_RQ.send_Serial(context, (byte) 0x00);

            case 2:
//
                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 3:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 4:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 5:

                week_RQ.send_Serial(context, (byte) 0x00);


                break;

            case 6:

                week_RQ.send_Serial(context, (byte) 0x00);


                break;

            case 7:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 8:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 9:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 10:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 11:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 12:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 13:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;

            case 14:

                week_RQ.send_Serial(context, (byte) 0x00);

                break;
        }

    }


       //此处获取定时开关是否开启
    public static List<String> get_Shared_switch() {

//        List<String> Shared_switch = null;

//        if (Shared_switch == null)
            List<String>  Shared_switch = new ArrayList<>();

        //user1早餐-睡前
        String Shared_flag1 = SharedPreferencesUtils.getString("Shared_flag1");
        String Shared_flag2 = SharedPreferencesUtils.getString("Shared_flag2");
        String Shared_flag3 = SharedPreferencesUtils.getString("Shared_flag3");
        String Shared_flag4 = SharedPreferencesUtils.getString("Shared_flag4");
        String Shared_flag5 = SharedPreferencesUtils.getString("Shared_flag5");
        String Shared_flag6 = SharedPreferencesUtils.getString("Shared_flag6");
        String Shared_flag7 = SharedPreferencesUtils.getString("Shared_flag7");


        Shared_switch.clear();
        Shared_switch.add(Shared_flag1);
        Shared_switch.add(Shared_flag2);
        Shared_switch.add(Shared_flag3);
        Shared_switch.add(Shared_flag4);
        Shared_switch.add(Shared_flag5);
        Shared_switch.add(Shared_flag6);
        Shared_switch.add(Shared_flag7);


        return Shared_switch;
    }


     //此处获取定时的时间
    public static List<String> get_time() {

//        List<String> time = null;

        List<String>    time = new ArrayList<>();
        time.clear();
        //user1时间 早餐-睡前
        String user1_time1 = SharedPreferencesUtils.getString("user1_time1");
        String user1_time2 = SharedPreferencesUtils.getString("user1_time2");
        String user1_time3 = SharedPreferencesUtils.getString("user1_time3");
        String user1_time4 = SharedPreferencesUtils.getString("user1_time4");
        String user1_time5 = SharedPreferencesUtils.getString("user1_time5");
        String user1_time6 = SharedPreferencesUtils.getString("user1_time6");
        String user1_time7 = SharedPreferencesUtils.getString("user1_time7");


        time.add(user1_time1);
        time.add(user1_time2);
        time.add(user1_time3);
        time.add(user1_time4);
        time.add(user1_time5);
        time.add(user1_time6);
        time.add(user1_time7);


        return time;
    }

    //获取当前系统时间
    public static String getCalendar() {

        long time = System.currentTimeMillis();

        SimpleDateFormat format = new SimpleDateFormat("HH:mm");

        Date date = new Date(time);

        String t1 = format.format(date);

        return t1;
    }

//获取年月日
    public static String getCalendar_day() {

        long time = System.currentTimeMillis();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date(time);

        String t1 = format.format(date);

        return t1;
    }

}

又不懂的欢迎交流

 

 

上一篇:Linux ping不通外网报 Destination Host Unreachable


下一篇:[CentOS8]安装部署