后台默默的劳动者,探究服务
2016-05-18 08:36
417 查看
服务是什么
服务(Service)是Android中实现程序后台运行的解决方案,它非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。服务依赖于创建服务时所在的应用程序进程。
Android多线程
线程的基本用法
继承Threadclass MyThread extends Thread{ @Override public void run(){ //处理具体逻辑 } }
实现Runable接口
class MyThread implements Runnable{ @Override public void run(){ //实现具体逻辑 } }
匿名内部类形式
new Thread(new Runnable(){ @Override public void run(){ //实现具体逻辑 } }).start();
在子线程中更新UI
Android的UI是线程不安全的,如果想要更新应用程序里的UI元素,则必须在主线程中进行,否则就会出现异常。可使用Android中的异步处理机制
public class MainActivity extends Activity implements OnClickListener { public static final int UPDATE_TEXT = 1; private TextView text; private Button changeText; private Handler handler = new Handler)(){ public void handleMessage(Message msg){ switch (msg.what){ case UPDATE_TEXT: //进行UI操作 text.setText("Nice to meet you"); break; default: break; } } }; ...... @Override public void onClick(View v){ switch (v.getId()){ case R.id.change_text: new Thread(new Runnable(){ @Override public void run(){ Message message = new Message(); message.what = UPDATE_TEXT; handler.sendMessage(message); } )}.start(); break; default: break; } } }
当调用Handler的sendMessage()方法将这条Message发送出去,Handler就会收到这条Message,并在handleMessage中进行处理
解析异步消息处理机制
Android中的异步消息处理机制主要由四个部分组成,Message、Handler、MessageQueue和Looper。Message是在线程之间传递的消息,它可以在内部携带少量的信息用于不同线程间交换数据
Handler 顾名思义也就是处理者的意思,它主要是用于发送和处理消息的。
MessageQueue 是消息队列的意思,它主要用于存放所有通过 Handler 发送的消息。
Looper 是每个线程中的 MessageQueue 的管家,调用 Looper 的 loop()方法后,就会进入到一个无限循环当中,然后每当发现 MessageQueue 中存在一条消息,就会将它取出, 并传递到 Handler 的 handleMessage()方法中。 每个线程中也只会有一个 Looper 对象。
使用AsyncTask
AsyncTask将异步消息处理机制进行了封装AsyncTask是一个抽象类,需要用子类继承它,在继承时可以为AnyncTask指定三个泛型参数
Params:在执行AsyncTask时需要传入的参数,可以于在后台任务中使用
Progress:后台任务执行时,如果需要在界面上显示当前的进度,则使用这里指定的泛型作为进度单位。
Result:当任务执行完毕后,如果需要对结果进行返回,则使用这里指定的泛型作为返回值类型。
class DownloadTask extends AsyncTask<Void,Integer,Boolean>{ ...... }
还需重写AsyncTask中的方法
* onPreExecute():这个方法会在后台任务开始执行之前调用,用于进行一些界面上的初始化操作
* doInBackground(Params…):这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任务。任务一旦完成就可以通过 return 语句来将任务的执行结果返回,在此方法中不能进行UI操作
* onProgressUpdate(Progress…):当在后台任务中调用了 publishProgress(Progress…)方法后,这个方法就会很快被调用,方法中携带的参数就是在后台任务中传递过来的。在这个方法中可以对 UI 进行操作,利用参数中的数值就可以对界面元素进行相应地更新。
* onPostExecute(Result):当后台任务执行完毕并通过 return 语句进行返回时,这个方法就很快会被调用。返回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些 UI 操作
class DownloadTask extends AsyncTask<Void,Integer,Boolean>{ @Override protected void onPreExecute(){ progressDialog.show(); } @Override protected Boolean doInBackground(Void...params){ try{ while(true){ int downloadPercent = doDownload(); publishProgress(downloadPercent); if(downloadPercent >= 100){ break; } } }catch(Exception e){ return false: } return true; } @Override protected void onProgressUpdate(Integer... valuse){ //更新下载进度 progressDialog.setMessage("Downloaded " + values[0] + "%"); } @Override protected void onPostExecute(Boolean result){ //关闭进度对话框 progressDialog.dismiss(); //提示下载结果 if(result){ Toast.makeText(context, "Download succeeded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, " Download failed", Toast.LENGTH_SHORT).show(); } } }
服务的基本用法
定义一个服务
继承Service类class MyService extends Service{ @Override public IBinder (Intent intent){ return null; } }
重写Service中最常用的三个方法
onCreate():在服务创建时调用
onStartCommand():在服务启动时调用
onDestroy():在服务销毁时调用
在AndroidManifest.xml文件中注册服务
<service android:name=".MyService" > </service>
启动和停止服务
启动服务Intent startIntent = new Intent(this,MyService.class); startService(startIntent);
停止服务
Intent stopIntent = new Intent(this,MyService.class); stopService(stopIntent);
onCreate()和onStartCommand()的区别: onCreate()方法是在服务第一次创建的时候调用的,而 onStartCommand()方法则在每次启动服务的时候都会调用。
活动和服务进行通信
思路:专门创建一个Binder对象对下载功能进行管理public class MyService extends Service{ private DownloadBinder mBinder = new DownloadBinder(); class DownloadBinder extends 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; } ...... }
public class MainActivity extends Activity implements OnClickListener{ private Button startService; private Button stopService; private Button bindService; private Button unbindService; private MyService.DownloadBinder downloadBinder; private ServiceConnection connection = new ServiceConnection(){ @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { downloadBinder = (MyService.DownloadBinder) service; downloadBinder.startDownload(); downloadBinder.getProgress(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); …… bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); bindService.setOnClickListener(this); unbindService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { …… case R.id.bind_service: Intent bindIntent = new Intent(this, MyService.class); // 绑定服务 bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: // 解绑服务 unbindService(connection); break; default: break; } } }
服务的更多技巧
使用前台服务
public class MyService extends Service{ ...... @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); Log.d("MyService", "onCreate executed"); } ...... }
使用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()); } @Override public void onDestroy() { super.onDestroy(); Log.d("MyIntentService", "onDestroy executed"); } }
在onHandleIntent中可以处理一些具体的逻辑,而且不用担心ANR的问题,因为这个方法已经是在子线程是运行
相关文章推荐
- spring amqp rabbitmq fanout配置
- Scala学习笔记-apply方法
- Tree2cycle最小代价使一棵树构成环
- Postfix queue(邮件队列) 管理 mailq postsuper -d ALL
- 宝存科技发布Hyper-IO S3C企业级SATA SSD
- apache开启.htaccess及.htaccess的使用方法
- JavaScript console 用法大全
- 防止mysql重复插入记录的方法
- 史上最清晰的红黑树讲解(上)
- 函数 strtok_r
- 图解Oracle 12c 手动建库
- Object-C之继承
- 纹理特征
- Design Pattern - Structural Patterns - Adapter Pattern
- mysql故障排错临时打开通用日志和慢查询日志
- 动画设置参数,有数值,收藏了
- git 提交时,每次都需要输入用户名、密码
- MySQL学习笔记之二
- 动画设置参数,有数值,收藏了
- JDBC的储存过程 剖解