服务 IntentService 前台服务 定时后台服务
Activity
public class MainActivity extends ListActivity {private int intentNumber = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);List<String> mData = new ArrayList<String>(Arrays.asList("启动一个新的工作线程", "启动一个前台服务", //"设置一次性定时后台服务", "设置一个周期性执行的定时服务", "取消AlarmManager的定时服务"));ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);setListAdapter(mAdapter);}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {switch (position) {case 0:intentNumber++;Intent intent = new Intent(this, MyIntentService.class);Bundle bundle = new Bundle();bundle.putInt("intentNumber", intentNumber);intent.putExtras(bundle);startService(intent);//每次启动都会新建一个工作线程,但始终只有一个IntentService实例break;case 1:startService(new Intent(this, ForegroundService.class));break;case 2:Intent intent2 = new Intent(this, LongRunningService.class);intent2.putExtra("type", "onceAlarm");startService(intent2);break;case 3:Intent intent3 = new Intent(this, LongRunningService.class);intent3.putExtra("type", "repeatAlarm");startService(intent3);break;case 4:((AlarmManager) getSystemService(ALARM_SERVICE)).cancel(PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0));break;}}}
IntentService
/** 所有请求的Intent记录会按顺序加入到【队列】中并按顺序【异步】执行,并且每次只会执行【一个】工作线程,当所有任务执行完后IntentService会【自动】停止 */public class MyIntentService extends IntentService {public MyIntentService() { //必须实现父类的构造方法super("MyIntentService");}@Overrideprotected void onHandleIntent(Intent intent) {//注意,因为这里是异步操作,所以这里不能直接使用Toast。int intentNumber = intent.getExtras().getInt("intentNumber");//根据Intent中携带的参数不同执行不同的任务Log.i("bqt", "第" + intentNumber + "个工作线程启动了");try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}Log.i("bqt", "第" + intentNumber + "个工作线程完成了");}@Overridepublic IBinder onBind(Intent intent) {Log.i("bqt", "onBind");return super.onBind(intent);}@Overridepublic void onCreate() {Log.i("bqt", "onCreate");super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("bqt", "onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void setIntentRedelivery(boolean enabled) {super.setIntentRedelivery(enabled);Log.i("bqt", "setIntentRedelivery");}@Overridepublic void onDestroy() {Log.i("bqt", "onDestroy");super.onDestroy();}}
前台服务
/**所谓的前台服务就是状态栏显示的Notification,可以让Service没那么容易被系统杀死 */public class ForegroundService extends Service {@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();Notification.Builder localBuilder = new Notification.Builder(this).setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0)).setAutoCancel(false).setSmallIcon(R.drawable.ic_launcher).setTicker("Foreground Service Start").setContentTitle("前台服务").setContentText("正在运行...");startForeground(1, localBuilder.build());}@Overridepublic void onDestroy() {Log.i("bqt", "onDestroy");super.onDestroy();}}
定时后台服务
public class LongRunningService extends Service {public static final int anHour = 3 * 1000;//设置每隔3秒钟打印一次时间@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {//定时任务为:发送一条广播。在收到广播后启动本服务,本服务启动后又发送一条广播……PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0);//使用【警报、闹铃】服务设置定时任务。CPU一旦休眠(比如关机状态),Timer中的定时任务就无法运行;而Alarm具有唤醒CPU的功能。AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);long triggerAtTime;//闹钟(首次)执行时间String type = intent.getStringExtra("type");if ("onceAlarm".equals(type)) {//)//设置在triggerAtTime时间启动由operation参数指定的组件。该方法用于设置一次性闹钟triggerAtTime = SystemClock.elapsedRealtime() + anHour;//相对于系统启动时间,Returns milliseconds since boot, including time spent in sleep.manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);} else if ("repeatAlarm".equals(type)) {//设置一个周期性执行的定时服务,参数表示首次执行时间和间隔时间triggerAtTime = System.currentTimeMillis() + anHour;//相对于1970……绝对时间,Returns milliseconds since boot, including time spent in sleep.manager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, anHour, pendingIntent);} else if ("work".equals(type)) {//开辟一条线程,用来执行具体的定时逻辑操作new Thread(new Runnable() {@Overridepublic void run() {Log.i("bqt", new SimpleDateFormat("yyyy.MM.dd HH-mm-ss", Locale.getDefault()).format(new Date()));}}).start();}/**type有五个可选值:AlarmManager.ELAPSED_REALTIME 闹钟在睡眠状态下不可用,如果在系统休眠时闹钟触发,它将不会被传递,直到下一次设备唤醒;使用相对系统启动开始的时间AlarmManager.ELAPSED_REALTIME_WAKEUP 闹钟在手机睡眠状态下会唤醒系统并执行提示功能,使用相对时间AlarmManager.RTC 闹钟在睡眠状态下不可用,该状态下闹钟使用绝对时间,即当前系统时间AlarmManager.RTC_WAKEUP 表示闹钟在睡眠状态下会唤醒系统并执行提示功能,使用绝对时间AlarmManager.POWER_OFF_WAKEUP 表示闹钟在手机【关机】状态下也能正常进行提示功能,用绝对时间,但某些版本并不支持! */return super.onStartCommand(intent, flags, startId);}}
广播接收者
public class AlarmReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context, "定时任务已经执行了", Toast.LENGTH_SHORT).show();Intent workIntent = new Intent(context, LongRunningService.class);workIntent.putExtra("type", "work");context.startService(workIntent);}}
清单文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.bqt.intentservice"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="17"android:targetSdkVersion="21" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><serviceandroid:name=".MyIntentService"android:exported="false" ><intent-filter><action android:name="com.test.intentservice" /></intent-filter></service><service android:name=".ForegroundService" /><service android:name=".LongRunningService" /><receiver android:name=".AlarmReceiver" /></application></manifest>
服务 IntentService 前台服务 定时后台服务的更多相关文章
- .NET 使用自带 DI 批量注入服务(Service)和 后台服务(BackgroundService)
今天教大家如何在asp .net core 和 .net 控制台程序中 批量注入服务和 BackgroundService 后台服务 在默认的 .net 项目中如果我们注入一个服务或者后台服务,常规的 ...
- Android : App客户端与后台服务的AIDL通信以及后台服务的JNI接口实现
一.APP客户端进程与后台服务进程的AIDL通信 AIDL(Android Interface definition language-“接口定义语言”) 是 Android 提供的一种进程间通信 ( ...
- CentOS后台服务管理类
目录 一.service 后台服务管理(临时,只对当前有效) 二.chkconfig 设置后台服务的自启配置(永久) 三.CentOS7 后添加的命令:systemctl 一.service 后台服务 ...
- 答CsdnBlogger问-关于定时和后台服务问题
本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 前段时间写了不少博客,在问答页面也陆续回答几十个问题,之后Csdn乙同学找到我,说要推荐我参加问答类 ...
- Android Services (后台服务)
一.简介 服务是可以在后台执行长时间运行的应用程序组件,它不提供用户界面. 另一个应用程序组件可以启动一个服务,并且即使用户切换到另一个应用程序,它仍然在后台运行. 另外,组件可以绑定到一个服务来与它 ...
- Android 三级联动选择城市+后台服务加载数据库
技术渣,大家将就着看 首先我们需要一个xml数据保存到数据库,这里我从QQ下面找到一个loclist.xml文件 <CountryRegion Name="中国" Code= ...
- highchart访问一次后台服务返回多张图表数据
本文承接上一篇,我们制作动态图表的时候,往往需要的不止一张图表,如果每张图表都与服务接口做一次交互的话未免太过频繁,这无论对前后还是后台都是一种压力,本文介绍一种一次访问返回多组数据的方式来减少前台与 ...
- Android之后台服务判断本应用Activity是否处于栈顶
在Android开发中,我们经常想知道是否自己的服务处于后台运行中,因为在后台运行的服务器优先级会降低,也就极有可能会被系统给回收掉,有什么好办法呢?Google推荐我们将服务运行到前台,如何知道服务 ...
- .NET Core 中的通用主机和后台服务
简介 我们在做项目的时候, 往往要处理一些后台的任务. 一般是两种, 一种是不停的运行,比如消息队列的消费者.另一种是定时任务. 在.NET Framework + Windows环境里, 我们一般会 ...
随机推荐
- ORACLE的CONNECT和RESOURCE角色权限
最近在处理数据库的用户权限问题,之前惯性思维,觉得给用户授权RESOURCE权限之后,用户的一般权限都会有,等到发现用户有RESOURCE角色,却没有创建视图的权限之后,才发现这部分还是一知半解啊,所 ...
- 【转】深入理解Java内存模型(五)——锁
锁的释放-获取建立的happens before 关系 锁是java并发编程中最重要的同步机制.锁除了让临界区互斥执行外,还可以让释放锁的线程向获取同一个锁的线程发送消息. 下面是锁释放-获取的示例代 ...
- C程序第二章节:算法
1.主要讲了:算法,3种基本结构化的算法(顺序,选择,循环结构),N-S流程图表示算法,伪代码表示算法. 2.输入10个数,输出其中最大的一个数. #include <stdio.h>in ...
- jquery与discuz冲去的解决方法
把相应的JQUERY代码天下如下代码: <script type="text/javascript"> jQuery.noConflict(); </script ...
- ACM、OI等比赛中的程序对拍问题
多年前请教于ZXYTIM(zxy)大牛,现在把windows环境下的版本贴出来. 手动数据调试效率太低,程序对拍还是非常实用的,特别适用于OI.蓝桥杯等这些比赛规则.可以用于暴力与AC算法之间的对拍. ...
- 转:解决方案your project contains error s please fix them before running your application
文章来自于:http://www.mythroad.net/2013/08/05/%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88your-project-contains-e ...
- MetaData元数据
一.基础 定义:数据库.表.列相关信息的描述. 何时使用:想取得对数据库的信息时使用. 一]数据库元数据——通过DataBaseMetaData DataBaseMe ...
- JAVA中,数组的操作与排序
自己写了正向反向的冒泡排序,还用了静态和NEW方法实现. import java.util.Arrays; public class HelloJava { public static void ma ...
- 使用Userlock监控用户访问 增强学校网络安全
随着网络技术的不断进步,一方面,拥有广泛教学资源的各大大中院校纷纷升级校园网络技术,保护学校的网络安全.另一方面,网络安全面临的威胁也层出不穷.面对来自网络内外的安全威胁,负责中小学.大学院校网络安全 ...
- BZOJ1690: [Usaco2007 Dec]奶牛的旅行
1690: [Usaco2007 Dec]奶牛的旅行 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 552 Solved: 286[Submit][St ...
