最近有个项目的要求是在程序退出之后,任然可以每天定时发通知,我们可以想下,其实就是后台开一个服务,然后时间到了就发下通知。

1.首先我们需要用到Service类。

先上代码在慢慢解释

 package com.example.androidnotification;

 import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log; public class PushService extends Service { static Timer timer = null;
//清除通知
public static void cleanAllNotification() {
NotificationManager mn= (NotificationManager) MainActivity.getContext().getSystemService(NOTIFICATION_SERVICE);
mn.cancelAll();
if (timer != null) {
timer.cancel();
timer = null;
}
} //添加通知
public static void addNotification(int delayTime,String tickerText,String contentTitle,String contentText)
{
Intent intent = new Intent(MainActivity.getContext(), PushService.class);
intent.putExtra("delayTime", delayTime);
intent.putExtra("tickerText", tickerText);
intent.putExtra("contentTitle", contentTitle);
intent.putExtra("contentText", contentText);
MainActivity.getContext().startService(intent);
} public void onCreate() {
Log.e("addNotification", "===========create=======");
} @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
} public int onStartCommand(final Intent intent, int flags, int startId) { long period = 24*60*60*1000; //24小时一个周期
int delay=intent.getIntExtra("delayTime",0);
if (null == timer ) {
timer = new Timer();
}
timer.schedule(new TimerTask() { @Override
public void run() {
// TODO Auto-generated method stub
NotificationManager mn= (NotificationManager) PushService.this.getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(PushService.this);
Intent notificationIntent = new Intent(PushService.this,MainActivity.class);//点击跳转位置
PendingIntent contentIntent = PendingIntent.getActivity(PushService.this,0,notificationIntent,0);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker(intent.getStringExtra("tickerText")); //测试通知栏标题
builder.setContentText(intent.getStringExtra("contentText")); //下拉通知啦内容
builder.setContentTitle(intent.getStringExtra("contentTitle"));//下拉通知栏标题
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
mn.notify((int)System.currentTimeMillis(),notification);
}
},delay, period); return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy(){
Log.e("addNotification", "===========destroy=======");
super.onDestroy();
}
}

自定义了一个类PushService继续Service,定义了两个类来实现添加通知和取消通知

//delayTime 延迟多久执行。

//tickerText

//contentTitle 通知栏的标题

//contentText 通知栏的内容

addNotification(int delayTime,String tickerText,String contentTitle,String contentText)

//清除通知

cleanAllNotification()

====================================

Service的启动,startService来启动服务只执行一次onCreate方法,但是每次调用一次startService就会执行一次onStartCommand函数。

2.注册服务类

在AndroidManifest.xml中的application字段中加入如下信息来注册这个服务类。

<service android:enabled="true" android:name=".PushService" android:process="system"></service>

这边有一点非常重要的是 android:process="system" ,设置为system,否则按退出键使用如下方式来执行会导致程序崩溃,而且服务也会被终止,

android.os.Process.killProcess(android.os.Process.myPid());或者System.exit(0)

因为service是和主线程在一起的,主线程被终止了,服务线程也会停止掉,就无法在后台执行了,所以我们必须把服务注册到系统中。

我们启动服务使用startservice方式,因为使用bindservice会跟所绑定的context一起死亡的,bindservice的概念是"不求同生,但求同死",所以使用bindservice时候注意不能设置android:process="system"

工程源码

android 后台服务定时通知的更多相关文章

  1. Android后台服务拍照

    原文:https://blog.csdn.net/wurensen/article/details/47024961 一.背景介绍最近在项目中遇到一个需求,实现一个后台拍照的功能.一开始在网上寻找解决 ...

  2. Android后台服务拍照的解决方式

    一.背景介绍 近期在项目中遇到一个需求.实现一个后台拍照的功能. 一開始在网上寻找解决方式.也尝试了非常多种实现方式,都没有惬意的方案.只是确定了难点:即拍照要先预览,然后再调用拍照方法.问题也随之而 ...

  3. Service官方教程(5)后台服务发送通知、把服务变前台服务。

    1.Sending Notifications to the User (发送通知) Once running, a service can notify the user of events usi ...

  4. Android中如何像 360 一样优雅的杀死后台服务而不启动

    Android中,虽然有很多方法(API或者shell命令)杀死后台`service`,但是仍然有很多程序几秒内再次启动,导致无法真正的杀死.这里主要着重介绍如何像 360 一样杀死Android后台 ...

  5. 答CsdnBlogger问-关于定时和后台服务问题

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 前段时间写了不少博客,在问答页面也陆续回答几十个问题,之后Csdn乙同学找到我,说要推荐我参加问答类 ...

  6. 服务 IntentService 前台服务 定时后台服务

    Activity public class MainActivity extends ListActivity {     private int intentNumber = 0;     @Ove ...

  7. Android Services (后台服务)

    一.简介 服务是可以在后台执行长时间运行的应用程序组件,它不提供用户界面. 另一个应用程序组件可以启动一个服务,并且即使用户切换到另一个应用程序,它仍然在后台运行. 另外,组件可以绑定到一个服务来与它 ...

  8. Android 三级联动选择城市+后台服务加载数据库

    技术渣,大家将就着看 首先我们需要一个xml数据保存到数据库,这里我从QQ下面找到一个loclist.xml文件 <CountryRegion Name="中国" Code= ...

  9. Android : App客户端与后台服务的AIDL通信以及后台服务的JNI接口实现

    一.APP客户端进程与后台服务进程的AIDL通信 AIDL(Android Interface definition language-“接口定义语言”) 是 Android 提供的一种进程间通信 ( ...

随机推荐

  1. ==和equals的异同

    == 和 Equals 的区别 1. == 是一个运算符. 2.Equals则是string对象的方法,可以.(点)出来. 我们比较无非就是这两种 1.基本数据类型比较 2.引用对象比较 1.基本数据 ...

  2. Node.js学习 - Modules

    创建模块 当前目录:hello.js, main.js // hello.js exports.world = function() { // exports 对象把 world 作为模块的访问接口 ...

  3. setAttribute的兼容性

    class和className兼容方法: object.setAttribute("class","content") 在IE8.Chrome.火狐.Opera ...

  4. 快速部署Python应用:Nginx+uWSGI配置详解

    在PHP里,最方便的就是deployment了,只要把php文件丢到支持PHP的路径里面,然后访问那个路径就能使用了:无论给主机添加多少PHP应用,只要把目录改好就没你的事了,完全不用关心php-cg ...

  5. 代码异味---Code smell

    程序员应该竭尽全力去写那些重复的代码.以下几点是我目前最需要改进的地方. 重复代码: 相同或者相似的代码存在于一个以上的地方. 长方法: 一个非常长的方法.函数或者过程. 巨类: 一个非常庞大的类. ...

  6. Elkstack2.0部署

    部署步骤如下: 1.1 资源拷贝 1 jdk1.8 2 kafka 3 kafka-manager 1.2 jvm 配置 vim /etc/profile.d/java.sh JAVA_HOME=/u ...

  7. uploadify在IE6下的问题

    上传插件uploadify,在IE8下运行的没有问题.转到IE6下时,就不能上传了. 把浏览器的“检查所存网页的较新版本” 设置为“每次访问网页时 ”就没有问题,如果设置为“自动 ”,IE6下就不能上 ...

  8. Java与C#的比较学习

    http://www.cnblogs.com/javathread/archive/2012/08/11/2634893.html 我在大学学的是C语言,自学和选修的是C++,刚毕业也搞过几天Jsp, ...

  9. Mac linux 安装memcached服务 用法

    今天在Mac上安装memcached服务的时候 由于安装memcached之前需要安装libevent依赖包 所以使用brew install libevent 安装过程中报错 Warning: Yo ...

  10. ACL in 和 out 区别 (重要)

    acl中in和out的区别   in和out是相对的,比如: A(s0)-----(s0)B(s1)--------(s1)C   www.2cto.com   假设你现在想拒绝A访问C,并且假设要求 ...