@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) //任何有网络的状态
.setPersisted(true) //系统重启后保留job
.setPeriodic(1000 * 60 * 60 * 24) //这里的单位是毫秒,1000 * 60 * 60 * 24代表一天(24小时)
.build();
jobScheduler.schedule(jobInfo);
} catch (Exception ex) {
Log.e("scheduleNotifications failure");
}
}
}
@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;
//检查距离用户上一次启动app是否过了一定时间
if(intervalSinceLastLaunch > 1000 * 60 * 60 * 24) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(NotificationService.this)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("我的app")
.setContentText("又有新的内容上线了,快来我们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;
}
}
<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" />
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有