android每日定时推送通知,Android使用JobScheduler定期推送本地通知实例代码

Android5.0之后提供了JobService和JobScheduler,用于在稍后的某个时间点或者当满足某个特定的条件时执行一个任务。使用JobScheduler,我们可以在用户一段时间没有使用我们的app的情况下,推送本地通知来提高app的用户留存率。废话不多说,上代码:

先在app的MainActivity启动时用JobScheduler来schedule一个job。注意在onCreate中我们把用户启动app的时间记录在了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) //任何有网络的状态

.setPersisted(true) //系统重启后保留job

.setPeriodic(1000 * 60 * 60 * 24) //这里的单位是毫秒,1000 * 60 * 60 * 24代表一天(24小时)

.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;

//检查距离用户上一次启动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;

}

}

最后需要在Manifest中注册我们的service和申请相关的权限:

android:permission="android.permission.BIND_JOB_SERVICE" />

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python是一种功能强大的编程语言,具有简单易学、灵活性高等特点,非常适合开发自动化任务。Push Plus是一款推送服务,可以实现向微信、QQ、邮箱等多个平台推送消息的功能。在日常学习和工作中,很多人需要及时掌握每日任务完成情况,这就需要使用Python来实现Push Plus推送任务完成情况。 首先,需要在Push Plus官网上注册账号,并创建自己的推送通道。然后,可以使用Python的requests库来发送POST请求,将任务完成情况推送到Push Plus通道中。代码如下: ```python import requests # Push Plus通道Token token = 'your_token' # 推送标题 title = '每日任务完成情况' # 推送内容 content = '今日任务已完成!' # 推送方式 template = 'html' # 发送POST请求 response = requests.post('http://pushplus.hxtrip.com/send', data={'token': token, 'title': title, 'content': content, 'template': template}) ``` 其中,token是在Push Plus官网上创建的推送通道的Token,title是推送标题,content是推送内容,template是推送消息的格式,可以是txt或html。以上代码使用的是html格式。 为了实现每日自动推送任务完成情况,可以利用Python的定时任务库,比如APScheduler,设置每日定时发送推送请求。代码如下: ```python from apscheduler.schedulers.blocking import BlockingScheduler # 创建定时任务 scheduler = BlockingScheduler() # 定义任务 def push_task(): # Push Plus通道Token token = 'your_token' # 推送标题 title = '每日任务完成情况' # 推送内容 content = '今日任务已完成!' # 推送方式 template = 'html' # 发送POST请求 response = requests.post('http://pushplus.hxtrip.com/send', data={'token': token, 'title': title, 'content': content, 'template': template}) print(response.text) # 添加定时任务,每天8点执行 scheduler.add_job(push_task, 'cron', hour=8) # 启动定时任务 scheduler.start() ``` 以上代码使用APScheduler定时任务库,并设置每天早上8点执行任务。当任务完成后,会自动将任务完成情况推送到Push Plus通道中,从而方便在手机或电脑上收到及时的提醒。 综上所述,Python和Push Plus可以很好地配合使用,实现每日任务完成情况的自动推送。有了这个工具,我们可以更好地管理自己的工作和学习,提高效率和自律性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值