$《第一行代码:Android》读书笔记——第9章 服务
class MyThread extends Thread{
public void run( ){
//执行耗时操作
}
}
new MyThread( ).start( );
(2)实现Runnable接口:
class MyRunnable implements Runnable{
public void run( ){
//执行耗时操作
}
}
new Thread(new MyRunnable).start( );
(3)使用匿名类:
new Thread(new Runnable( ){
public void run( ){
//执行耗时操作
}
}).start( );
2、Android不允许在子线程中更新UI,只能在主线程中更新。
private Handler handler = new Handler( ){
public void handleMessage(Message msg){
switch(msg.what){ //msg的what字段是一个标志字段,整型
case xxx:
//在这里可以进行UI操作
textView.setText("Change text succeed!") //改变textView的字符
break;
default:
break;
}
}
}
(2)在子线程中需要进行UI操作时(如按钮点击事件中),创建一个Message对象,并通过Handler对象的sendMessage方法将该消息发送出去,比如:
public static final int UPDATE_TEXT = 1; //修改UI的标志值
......
@Override
public void onClick(View v){
switch(v.getId( )){
case R.id.chage_text_btn:
new Thread(new Runnable( ){
@Override
public void run( ){
Message msg = new Message( );
msg.what = UPDATE_TEXT ;
handler.sendMessage(msg);
}
}).start( );
break; default:
break;
}
}

class MyAsyncTask extends AsyncTask<Params, Progress, Result>
(五)Service
1、定义Service:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}
2、Service类中有一个抽象方法onBind,还有三个常用方法:
<application
... >
<service android:name=".MyService" >
</service>
...
</application>
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
(2)停止:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
5、Activity和Service通信:
(1)在Service中安插内线Binder,并在onBind方法中发送这个内线:
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder { //自定义Binder,模拟下载功能
public void startDownload() {
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
... //其他方法
}
(2)在Activity中创建内线及ServiceConnection,其中的onServiceConnected方法即可接收内线IBinder并通过向下转型获取Binder:
...
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
} @Override
public void onServiceDisconnected(ComponentName name) { };
};
...
(3)在合适的时候(如按钮的点击事件等)绑定Activity与Service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); //BIND_AUTO_CREATE指当绑定后,自动创建Service
(4)解除绑定:
if(connection != null){
unbindService(connection);
}
startService( )
onCreate( )
onStartCommand( )
onDestory( )
bindService( )
unbindService( )
stopService( )
stopSelf( ) //在Service中任何地方都可以用这个方法结束服务本身
onBind( )
(3)如果startService( )和bindService( )都调用了,那么必须同时满足unbindService( )和stopService( )都被调用才会执行onDestory( )方法。
7、前台Service:在系统状态栏中一直显示的可见Service,只需在Service的onCreate方法中添加如下代码即可(其实是通知的用法):
@Override
public void onCreate() {
super.onCreate();
...
Notification notification = new Notification(R.drawable.ic_launcher,
"Notification comes", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title",
"This is content", pendingIntent);
startForeground(1, notification);
}
8、IntentService:
服务的代码默认都是在主线程中的,如果直接在服务里去处理一些耗时逻辑,就很容易出现ANR(Application Not Responding)的情况。这时就可以方便的使用已经把多线程封装好的IntentService类:
public class MyIntentService extends IntentService {
public MyIntentService() { //需要一个无参的构造方法,调用父类的有参构造方法
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) { //这个方法默认在子线程中运行
// 打印当前线程ID
Log.d("MyIntentService", "Thread id is "
+ Thread.currentThread().getId());
// 在这里已经是在子线程中运行了,可以执行一些耗时操作,但不能执行UI操作
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}
}
IntentService在任务处理完后,会自动调用onDestory方法,不用再去人工调用unbindService或stopService方法。其他用法和普通Service一样。
(六)Service最佳实践:后台定时任务
import java.util.Date; import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log; public class LongRunningService extends Service { @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
//创建子线程打印当前时间,模拟定时任务
new Thread(new Runnable() {
@Override
public void run() {
Log.d("LongRunningService",
"executed at " + new Date().toString());
}
}).start();
//1.创建AlarmManager
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int aMinute = 60 * 1000; // 一分钟的毫秒数
long triggerAtTime = SystemClock.elapsedRealtime() + aMinute;
//2.创建跳到广播接收器的Intent
Intent i = new Intent(this, AlarmReceiver.class);
//3.创建PendingIntent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//4.使用AlarmManager的set方法
//第一个参数:指定工作类型,有四种:ELAPSED_REALTIME_WAKEUP表示定时任务触发时间从
//系统开机算起,会唤醒CPU;ELAPSED_REALTIME,同ELAPSED_REALTIME_WAKEUP,但不会唤醒CPU;
//RTC表示从1970-1-1 00:00算起,不会唤醒CPU,RTC_WAKEUP同RTC,但会唤醒CPU。
//注:唤醒CPU和唤醒屏幕是不同的概念。
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId);
}
}
3、创建AlarmReceiver类:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; public class AlarmReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, LongRunningService.class);
context.startService(i); //反过来再启动服务,交替循环进行下去
}
}
4、在活动中启动服务:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); Intent i = new Intent(this, LongRunningService.class);
startService(i);
}
}
5、在AndroidManifest.xml中注册服务和广播接收器。
【本章结束】
随机推荐
- openWRT自学---针对backfire版本的主要目录和文件的作用的分析整理
特别说明:要编译backfire版本,一定要通过svn下载:svn co svn://svn.openwrt.org/openwrt/branches/backfire,而不能使用http://dow ...
- 修改Nginx与Apache上传文件大小限制
一.修改Nginx上传文件大小限制 我们使用ngnix做web server的时候,nginx对上传文件的大小有限制. 当超过大小的时候会报413错误. 这个时候我们要修改nginx参数. sudo ...
- spring cloud与K8S
链接:https://www.zhihu.com/question/50806354/answer/139653085 spring cloud +docker 当然没有问题,只是当我们搭建集群实现高 ...
- Eclipse 创建 XML 文件
Eclipse 创建 XML 文件 打开新建 XML 文件向导 你可以使用新建 XML 文件向导来创建 XML 文件.打开向导的方式有: 点击 File 菜单并选择 New > Other 点击 ...
- 更新mac系统和更新到Xcode7.3版本出现的: cannot create __weak reference in file using manual reference counting
之前的编程没有遇到过,应该是苹果官方那边又做了新规吧. 不过不要紧,只要根据这个就能解决报错问题. Set Build Settings -> Apple LLVM 7.1 - Languag ...
- 拍照权限,GPS权限的控制
最近项目中会遇到一些手机用户权限的问题,从网上百度了一下,发现有一些方法不能解决判断用户权限的是否开关,下面我就介绍两种权限的判断 1 拍照的权限控制 public static boolean is ...
- Android开发:《Gradle Recipes for Android》阅读笔记(翻译)4.1——编写自己的任务
问题: 你想用自己的任务定制gradle的构建过程. 解决方案: 在gradle的build文件里面增加task元素.用Android插件支持的extra属性使得开发更容易. 讨论: Gradle的D ...
- Cocos2d-x Lua中Sprite精灵类
精灵类是Sprite,它的类图如下图所示. Sprite类图 Sprite类直接继承了Node类,具有Node基本特征.此外,我们还可以看到Sprite类的子类有:PhysicsSprite和Skin ...
- EasyNVR无插件直播流媒体服务器云端集中管控的EasyNVS云管理平台安装使用文档
EasyNVS - EasyNVR云端集中管理服务 EasyNVS云管理平台是一套专门用于集中化管理EasyNVR 的解决方案. EasyNVR 采用主动注册的方式接入到 EasyNVS, 再由 Ea ...
- Object类有哪些公用方法?
Object是所有类的父类,任何类都默认继承Object. clone 保护方法,实现对象的浅复制,只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedExce ...