Android Service使用技巧
来源:互联网 发布:linux 清理缓存 目录 编辑:程序博客网 时间:2024/05/17 20:37
Android Service 使用技巧
使用前台服务
使用IntentService
使用前台服务
前台服务与普通服务的区别。普通服务在当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务,而前台服务会一直保持运行状态,而且会在系统的状态栏一直显示一个正在运行的图标。下拉状态栏后可以看到详细的信息。
package com.example.scott.frontservice;import android.annotation.TargetApi;import android.app.Notification;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.Build;import android.os.IBinder;import android.support.annotation.Nullable;import android.util.Log;/** * Created by SCOTT on 2016/7/24. */public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onCreate() { super.onCreate(); Intent notificationIntent = new Intent(this,MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0); Notification notification = new Notification.Builder(this) //没加setSmallIcon()方法就不显示设置的通知图标 .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("scott") .setContentText("la la la") .setContentIntent(pendingIntent) .build(); //在这里用startForeground()代替原理通知中的notify()的方法。 startForeground(1, notification); Log.d("MyService","onCreate executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d("MyService","onDestroy executed"); }}
调用startForeground() 就可以让MyService变成一个前台服务,
如图:
使用IntentService
为什么要使用IntentService 。比如我们想执行一个计时的操作,在计时完成后服务自动关闭。正常的做法是在onStartCommand()中创建一个线程去处理集体的耗时的操作,然后再线程处理完结束的时候 加上stopSelf(); new Thread(){
public void run(){
//处理具体的逻辑
stopSelf();
}
}
现在Android专门提供了一个IntentService类来完成上面的操作。
public class MyIntrentService extends IntentService { public MyIntrentService(){ super("MyIntentService");//调用父类中的有参构造函数 } @Override protected void onHandleIntent(Intent intent) { Log.d("MyIntentService","Thread id is"+Thread.currentThread().getId()); } @Override public void onDestroy() { super.onDestroy(); Log.d("MyIntentService","onDestroy executed"); }}
启用Service 后的调试日志输出结果如图
日志中主线程与服务的线程不是同一个线程。然后服务运行结束后就自动停止了。
好了就到这里了,以后遇到别的继续补充。
关注微信公众号,每天都有优质技术文章,搞笑GIF图片推送哦。
2016-7-25
Scott
0 0
- Android Service使用技巧
- Android技巧:使用Service还是Thread
- Service使用技巧
- Service使用技巧,一些不为人知的功能 [移动平台 Android]
- Android Service更多的技巧
- Reporting Service 2005 使用技巧
- Android Service的使用
- Android Service 的使用
- Android service的使用
- Android Service的使用
- Android中的Service使用
- Android:使用service
- Android Service 使用实例
- android之service使用
- Android学习:Service使用
- android 使用service
- Android Service 的使用
- android service使用
- session失效的几种方式
- 程序猿务必要提供自身英语能力,从现在开始!
- 性能不好怎么办?对着清单撸一遍
- 对数据结构的一些了解
- 树状数组 改段求点
- Android Service使用技巧
- 织梦dedecms TAG列表按最新发布时间排序的解决方法
- C++知识点
- Java中对象和对象引用
- 为织梦cms列表页文章缩略图添加alt属性的方法
- 阿牛的EOF串
- 织梦DedeCMS实现缩略图不拉伸变形的方法
- POJ 2524 - Ubiquitous Religions
- 数据结构