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

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"

工程源码

最新文章

  1. SpringData —— HelloWorld
  2. JavaScript 表单验证
  3. SQLSERVER 复制同一张表的递归结构
  4. Spark Streaming中动态Batch Size实现初探
  5. 推荐几个好用的在线svn空间
  6. 自学 iOS – 三十天三十个 Swift 项目
  7. js笔记----(运动)分享 隐藏/显示
  8. N-Queens II
  9. 提升web响应速度的思路
  10. mysql中存不进去json_encode格式的数据
  11. 模式识别 - 处理多演示样例学习(MIL)特征(matlab)
  12. iOS 检测版本更新
  13. 測试JSON RPC远程调用(JSONclient)
  14. Asp.net MVC3 中,动态添加filter
  15. Web层框架对网站中所有异常的统一解决
  16. 201521123063 《Java程序设计》 第10周学习总结
  17. 7.10 break.c 程序
  18. Signalr实现消息推送
  19. linux shell习题
  20. SQL-22 统计各个部门对应员工涨幅的次数总和,给出部门编码dept_no、部门名称dept_name以及次数sum

热门文章

  1. Fragment里面嵌套Fragment的问题
  2. 基于手机传感器数据使用 CNN 识别用户行为的 Tensroflow 实现
  3. laravel提示Mcrypt PHP extension required
  4. c# 如何判断字符串中相同字符串的个数 (相同字符在字符串中出现的次数)
  5. android4.0蓝牙使能的详细解析(转)
  6. iptables原理详解以及功能说明
  7. ajax编程**
  8. 二部图(二分图判定--dfs)
  9. fuel 6.1自动推送3控高可用centos 6.5 juno环境排错(一)
  10. 高并发数据库之MySql性能优化