代码之家  ›  专栏  ›  技术社区  ›  Hadis

Android-JobScheduler的setPeriodic无法工作

  •  7
  • Hadis  · 技术社区  · 6 年前

    我编写了一个应用程序,用于创建和提醒使用本地SqliteDatabase的任务。 我编写了一个jobScheduler服务来检查设备时间和日期以及数据库中的任务,如果匹配项显示推送通知。 我还想让服务在后台运行,每5秒钟检查一次数据。 但是当我写作的时候

    建设者setPeriodic(5000); 建设者setPersisted(true);

    服务停止检查数据。

    这是我的密码

    主要活动

          public class MainActivity extends AppCompatActivity  {
    ImageButton plusImageBtn;
    DatabaseHelper databaseHelper;
    BottomNavigationView navigation;
    Toolbar toolbar;
    private ComponentName mServiceComponent;
    private int jobId=0;
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String WORK_DURATION_KEY =
            BuildConfig.APPLICATION_ID + ".WORK_DURATION_KEY";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        plusImageBtn = (ImageButton) findViewById(R.id.plusImagBtn);
        toolbar= (Toolbar) findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
    
        mServiceComponent = new ComponentName(this, JobSchedulerService.class);
    
        databaseHelper= new DatabaseHelper(this);
        navigation.setOnNavigationItemSelectedListener
                (new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    
                        Fragment selectedFragment = null;
                        switch (item.getItemId()) {
                            case R.id.navigation_calendar:
                                selectedFragment = new CalendarFragment();
                                break;
                            case R.id.navigation_home:
                                selectedFragment = new ViewListContents();
                                break;
                        }
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.frame_layout, selectedFragment);
                        transaction.commit();
                        return true;
    
                    }
                });
        FragmentTransaction transaction = 
         getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout,new  ViewListContents());
        transaction.commit();
        scheduleJob();
    
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        // Start service and provide it a way to communicate with this class.
        Intent startServiceIntent = new Intent(this, JobSchedulerService.class);
        startService(startServiceIntent);
    }
    
    @Override
    protected void onStop() {
        stopService(new Intent(this,JobSchedulerService.class));
        super.onStop();
    }
    
    public void scheduleJob() {
        JobInfo.Builder builder = new JobInfo.Builder(jobId++, mServiceComponent);
     //  builder.setPeriodic(5000);
       // builder.setPersisted(true);
    
        builder.setMinimumLatency(1000);
        builder.setOverrideDeadline(1000);
    
        // Extras, work duration.
        PersistableBundle extras = new PersistableBundle();
        extras.putLong("",5000);
        builder.setExtras(extras);
        // Schedule job
        Log.d(TAG, "Scheduling job");
        JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            tm.schedule(builder.build());
        Toast.makeText(this, "Scheduling job  ", Toast.LENGTH_SHORT).show();
    
    }}
    

    JobSchedulerService

      public class JobSchedulerService extends JobService {
    int id;
    String stringId;
    String date;
    String taskDate,taskTitle,taskTime,sepYear,sepMonth, 
     sepDay,convert,DeviceDate;
    Cursor taskDateCursor;
    DatabaseHelper databaseHelper;
    Roozh roozh;
    String[] seperatedString;
    int iYear,iMonth, iDay;
    SimpleDateFormat dateFormat,  timeFormat;
    private static final String TAG = JobSchedulerService.class.getSimpleName();
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Service created");
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service destroyed");   }
    
    @Override
    public boolean onStartJob(final JobParameters params) {
        stringId = String.valueOf(params.getJobId());
        id = params.getJobId();
        final long duration = params.getExtras().getLong(WORK_DURATION_KEY);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                databaseHelper= new DatabaseHelper(getApplicationContext());
    
                taskDateCursor=databaseHelper.getDateForNotification();
                if (taskDateCursor.moveToFirst()){
                    do {
                        taskTitle=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL2));
                        taskDate=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL3));
                        taskTime=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL4));
    
    
                        roozh= new Roozh();
                        seperatedString=taskDate.split("/");
                        sepYear=  seperatedString[0];
                        sepMonth=  seperatedString[1];
                        sepDay=  seperatedString[2].trim();
                        iYear= Integer.parseInt(sepYear);
                        iMonth= Integer.parseInt(sepMonth);
                        iDay= Integer.parseInt(sepDay);
                        roozh.PersianToGregorian(iYear,iMonth,iDay);
                        convert= roozh.toString();
                        dateFormat= new SimpleDateFormat(
                                "yyyy-MM-dd", Locale.getDefault());
                        DeviceDate= dateFormat.format(new Date());
                        timeFormat=new SimpleDateFormat("HH:m",Locale.getDefault());
    
                        String  deviceTime=timeFormat.format(new Date());
    
                        RemoteViews remoteViews= new RemoteViews(getPackageName(),R.layout.notification);
                        remoteViews.setImageViewResource(R.id.notif_image, R.mipmap.ic_launcher);
                        remoteViews.setTextViewText(R.id.title,taskTitle);
                        remoteViews.setTextViewText(R.id.text,taskTime);
    
                        if (DeviceDate.equals(convert)  && deviceTime.equals(taskTime) ){
                            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                                    .setSmallIcon(R.drawable.drawable_circle)
                                    .setContent(remoteViews)
                                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                    .setColor(ContextCompat.getColor(getApplication(), R.color.primaryDarkColor))
                                    .setShowWhen(true)
                                    .setAutoCancel(true);
                            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
                            notificationManager.notify(0, mBuilder.build());
    
                        }
    
                        Log.i(TAG, "data " + DeviceDate+ "task" + convert+ " " + "dd" + " "+  taskTime + "dt" + "" + deviceTime);
                    }while (taskDateCursor.moveToNext());
                }            }
        }, duration);
        Log.i(TAG, "on start job: " + params.getJobId());
       return true;    }
    
    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i(TAG, "on stop job: " + params.getJobId());
        return true;    }
    
    4 回复  |  直到 6 年前
        1
  •  6
  •   Steve Miskovetz    6 年前

    我认为你的问题是你想执行工作的频率。在标准AOSP中,作业的最短时间为15分钟。因此,它可能不是适合您的API。报警管理器可能是您想要的,但每5秒设置一次报警是昂贵的。随着每次发布,谷歌也越来越多地限制后台服务。只是要记住一些事。

    请参见: JobScheduler not repeating job

        2
  •  2
  •   Rishabh Dhiman    5 年前

    setPeriodic(长间隔毫秒)仅适用于低于牛轧糖的设备 setPeriodic (long intervalMillis, long flexMillis) 适用于android版本Nougat及以上的设备。

        3
  •  0
  •   marc_s WardL    5 年前

    ScheduledThreadPoolExecutor是一个更好的选项。 任务可以按scheduleAtFixedRate或scheduleWithFixedDelay进行调度。

    参考号: https://developer.android.com/reference/kotlin/java/util/concurrent/ScheduledThreadPoolExecutor#schedule

        4
  •  0
  •   Prajwal Waingankar    4 年前

    请参考我的回答:

    https://stackoverflow.com/a/60295377/9166855

    最短时间为15分钟!