奥利奥日历的变化

时间:2018-04-02 18:37:59

标签: android android-calendar android-8.0-oreo

我曾经在清单中使用此代码获取日历更改:

    <receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PROVIDER_CHANGED" />
            <data android:scheme="content" />
            <data android:host="com.android.calendar" />
        </intent-filter>
    </receiver>

但Android 8 Oreo无法做到这一点。我读过它需要一份工作或类似的东西(我从未使用过工作,我不需要它们)。每当日历中发生更改时,任何人都可以键入作业示例。就像我上面的代码用来处理那个简单的广播接收器一样。

1 个答案:

答案 0 :(得分:2)

感谢CommosWare的提示,我能够做到这一点。我在这里输入完整的代码:

清单文件:

<service android:name=".MyReceiverAsJob"
         android:permission="android.permission.BIND_JOB_SERVICE" />

文件MyReceiverAsJob.java:

package my.package;        
import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.CalendarContract;
import android.widget.Toast;


@TargetApi(Build.VERSION_CODES.N)
public class MyReceiverAsJob extends JobService {
    private static final int iJobId = 1005; //Job Id
    final Handler mHandler = new Handler(); //Just to display Toasts

    static void schedule(Context oContext) {    
        ComponentName oComponentName = new ComponentName(oContext, clsJobServiceRecibidorDeGoogleCalendar.class);
        JobInfo.Builder oJobInfoBuilder = new JobInfo.Builder(ME_MYSELF_AND_I, oComponentName);
        final Uri CALENDAR_URI = Uri.parse("content://" + CalendarContract.AUTHORITY + "/");
        oJobInfoBuilder.addTriggerContentUri(new JobInfo.TriggerContentUri(CalendarContract.CONTENT_URI, JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
        oJobInfoBuilder.addTriggerContentUri(new JobInfo.TriggerContentUri(CALENDAR_URI, 0));
        JobScheduler jobScheduler = (JobScheduler) oContext.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(oJobInfoBuilder.build());
    }


    @Override
    public boolean onStartJob(JobParameters params) {

        DisplayToast("Calendar has been modified. Do some work!");

        schedule(this); //Reschedule to receive future changes
        return (false);
    }


    @Override
    synchronized public boolean onStopJob(JobParameters params) {
        return (false);
    }


    void DisplayToast(final CharSequence text) {
        mHandler.post(new Runnable() {
            @Override public void run() {
                Toast.makeText(clsJobServiceRecibidorDeGoogleCalendar.this, text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

我从我的前台服务中调用它:

MyReceiverAsJob.schedule(this);

它有效,但有时会在日历中没有任何改变的情况下调用它。如果我做错了什么,请告诉我。