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

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. as3 公式

    AS3缓动公式:sprite.x += (targetX - sprite.x) * easing;//easing为缓动系数变量sprite.y += (targetY - sprite.y) * ...

  2. mytest 截图

  3. Chapter 1 First Sight——18

    But at least he sent me to an empty desk at the back without introducing me to the class. 但是最后他给我最后面 ...

  4. laravel提示Mcrypt PHP extension required

    系统Ubuntu 安装Apache,php后发现laravel报 Mcrypt PHP extension required错误 解决办法: apt-get install php5-mcrypt c ...

  5. virtualbox, vt-s, rmmod kvm-intel

    http://blog.sina.com.cn/s/blog_4e7b97f00100fltu.html装完后,去下个jdk,坑爹的Oracle非要让老子注册,试了几次都没有成功,密码不合格拉,邮箱已 ...

  6. gen_compile.sql

    set echo off pagesize 0 feedback off define v_input_un       = &1define v_input_pw       = & ...

  7. Sonya and Problem Wihtout a Legend

    Sonya and Problem Wihtout a Legend Sonya was unable to think of a story for this problem, so here co ...

  8. ViewController 视图控制器

    [父视图控制器 addChildViewController:子视图控制器]; 在此,图控制器A添加了另一个图控制器B,那么A充当父视图控制器,B充当子视图控制器.父视图控制器充当了视图控制器容器的角 ...

  9. ubuntu配置openvpn

    http://www.zhixing123.cn/ubuntu/ubuntu-openvpn-settings-tutorial.html 本文介绍Ubuntu连接使用OpenVPN方法教程,Ubun ...

  10. mysql中变量character_set_connection的具体作用

    如题.通常的使用中,character_set_client,character_set_connection这两个变量的值是一样的,也就是说查询不需要进行编码转换.这样看来变量character_s ...