Android5.0之后提供了JobService和JobScheduler,用于在稍后的某個(gè)時(shí)間點(diǎn)或者當(dāng)滿足某個(gè)特定的條件時(shí)執(zhí)行一個(gè)任務(wù)寥假。使用JobScheduler如输,我們可以在用戶一段時(shí)間沒有使用我們的app的情況下之拨,推送本地通知來提高app的用戶留存率吊奢。廢話不多說盖彭,上代碼:
先在app的MainActivity啟動(dòng)時(shí)用JobScheduler來schedule一個(gè)job。注意在onCreate中我們把用戶啟動(dòng)app的時(shí)間記錄在了shared preference里面:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences.edit().putLong(Constants.SP_PARAM_LAST_LAUNCH, System.currentTimeMillis()).apply();
scheduleNotifications();
}
private void scheduleNotifications() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(getPackageName(), NotificationService.class.getName()))
.setRequiresCharging(false)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //任何有網(wǎng)絡(luò)的狀態(tài)
.setPersisted(true) //系統(tǒng)重啟后保留job
.setPeriodic(1000 * 60 * 60 * 24) //這里的單位是毫秒,1000 * 60 * 60 * 24代表一天(24小時(shí))
.build();
jobScheduler.schedule(jobInfo);
} catch (Exception ex) {
Log.e("scheduleNotifications failure");
}
}
}
然后是推送通知的NotificationService召边,這里SharedPreferences是用的dagger2依賴注入铺呵,不用dagger的可以直接用PreferenceManager.getDefaultSharedPreferences來獲得:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NotificationService extends JobService {
@DefaultSharedPref
@Inject
SharedPreferences sharedPreferences;
@Override
public boolean onStartJob(JobParameters params) {
try {
long lastLaunchTime = sharedPreferences.getLong(Constants.SP_PARAM_LAST_LAUNCH, -1);
if(lastLaunchTime > 0) {
long intervalSinceLastLaunch = System.currentTimeMillis() - lastLaunchTime;
//檢查距離用戶上一次啟動(dòng)app是否過了一定時(shí)間
if(intervalSinceLastLaunch > 1000 * 60 * 60 * 24) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(NotificationService.this)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("我的app")
.setContentText("又有新的內(nèi)容上線了,快來我們app看看吧!");
Intent resultIntent = new Intent(NotificationService.this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(NotificationService.this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
} catch (Exception ex) {
Log.e("Exception in NotificationService onStartJob");
}
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d("NotificationService onStopJob");
return true;
}
}
最后需要在Manifest中注冊(cè)我們的service和申請(qǐng)相關(guān)的權(quán)限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service android:name=".NotificationService"
android:permission="android.permission.BIND_JOB_SERVICE" />