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

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. Linux 监控文件事件

    某些应用程序需要对文件或者目录进行监控,来侦测其是否发生了某些事件.Linux很贴心的为我们提供了inotify API,也是Linux的专有. inotify API 在使用之前一定要有一个inot ...

  2. zencart url特殊字符处理

    1. 支持 在后台的seo url 将Outputw3c 改为false 2.删除特殊字符 这对于在少量的zen cart网站上处理少量的特殊字符可能还适用,实际上我们经常在导入产品数据时或者或少会带 ...

  3. 自己用wireshark 抓了个包,分析了一下

    我自把对应 ip 包的头部拿出来手动分析了一下 :)

  4. android脚步---UI界面修改,关于activity中增加按钮和监听

    增加按钮和监听,这个和上个不同在于,它不是在一个dialog里面,而是从新写了一个activity,因此需要先找到这个activity的入口. case R.id.checkframe: if (mC ...

  5. UIView 视图切换

    UIView之间常用视图之间切换方式 转载自:http://www.jianshu.com/p/0d53f9402c07 在平时编写代码的过程中,页面之间的跳转可以说就和MVC模式一样是开发必须的.但 ...

  6. [转]读取assets目录下的数据库文件

    在做Android应用的时候,不可避免要用到数据库.但是当我们把应用的apk部署到真机上的时候,已经创建好的数据库及其里边的数据是不能随着apk一起安装到真机上的. (PS:这篇博客解决了我前面博客中 ...

  7. 实现免密码输入 ssh 登录

    实现免密码输入 ssh 登录假设 A 为客户机器, B 为目标机:要达到的目的:A 机器 ssh 登录 B 机器无需输入密码:加密方式选 rsa|dsa 均可以,默认 dsa做法:1.登录 A 机器2 ...

  8. Java笔记(三)

    12. 字符串 String s1 = "abc"; String s2 = new String("abc"); s1在内存中有一个对象:s2在内存中有两个对 ...

  9. PAT1012

    To evaluate the performance of our first year CS majored students, 为了计算第一年计算机科学学生的表现 we consider the ...

  10. line-box(转)

    inline-block是什么? Inline-block是元素display属性的一个值.这个名字的由来是因为,display设置这个值的元素,兼具行内元素( inline elements)跟块级 ...