Android多线程编程方法及开启步骤

  

  作者:华清远见讲师

  实现线程的两种方式

  使用继承的方法

  class MyThread extends Thread{

  @Override

  public void run(){

  //处理具体的逻辑

  }

  }

  要启动这个线程,在主线程中新建一个该实例,调用其start()方法即可。

  使用实现Runnable借口的方式

  class MyThread implements Runnable{

  @Override

  public void run(){

  //处理具体的逻辑

  }

  }

  开启现成时,使用:

  MyThread myThread = new MyThread();

  new Thread(MyThread).start();

  匿名类的方法去实现Runnable也是一样的

  new Thread(new Runnalbe(){

  @Override

  public void run(){

  //处理具体逻辑

  }

  }).start();

  异步操作

  和很多的GUI库一样,Android的UI也是线程不安全的,所以,我们不能在子线程中更新UI元素。

  我们需要通过异步的操作通过子线程向主线程通信的方式来将UI更新的操作交给主线程来完成。

  Handler和Message结合传递的方法

  这里,有Message、Handler、MessageQueue和Looper在作用。

  1、Message是县城之间传递的消息。

  2、Handler是处理者,用于发送和处理消息

  3、MessageQueue是消息队列的意思,存放通过Handler发送的消息。

  4、Looper是每个线程中的MessageQueue的管家。​

  Handler handler = new Handler(){

  public void handleMessage(Message msg){

  switch (msg.what){

  case UPDATA_TEXT:

  txvHello.setText("Nice to meet you!");

  break;

  default:

  break;

  }

  }

  };

  8new Thread(new Runnable() {

  @Override

  public void run() {

  Message msg = new Message();

  msg.what = UPDATA_TEXT;

  handler.sendMessage(msg);

  }

  }).start();

  使用Async Task

  Async Task是一个抽象类,我们要使用它,就要先对他进行处理。

  3个参数:

  1、Params在执行AsyncTask时需要传入的参数,可用于在后台服务中使用。

  2、Progress如果需要在界面上显示当前的进度,使用这里的泛型作为进度单位。

  3、Result任务执行完毕后,对结果进行返回。​

  4个重写的方法:

  1、onPreExecute()

  2、DoInBackground(。。。)

  3、onProgressUpdate(。。。)

  4、onPostExecute(Result)​

  public class DownloadTask extendsAsyncTask{

  TextView txvDownloading;

  ProgressBar progressBar;

  @Override

  protected void onPreExecute() {

  super.onPreExecute();

  progressBar.setMax(100);

  }

  public DownloadTask(TextView txvDownloading, ProgressBar progressBar) {

  this.txvDownloading = txvDownloading;

  this.progressBar = progressBar;

  }

  @Override

  protected Integer doInBackground(Void... params) {

  int count = 0;

  for (int i =100; i > 0; i-- ){

  count++;

  publishProgress(count);

  try {

  Thread.sleep(500);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  return count;

  }

  @Override

  protected void onProgressUpdate(Integer... values) {

  int a = values[0];

  Log.d("TAG",a+"");

  progressBar.setProgress(a);

  }

  @Override

  protected void onPostExecute(Integer integer) {

  super.onPostExecute(integer);

  if(integer.equals(100)){

  txvDownloading.setText("Done");

  }else{

  txvDownloading.setText("downloading");

  }

  }

  }

  在Mainactivity中只需要写入:

  1new DownloadTask(txvShow, prgsDownload).execute();

  即可。

  服务

  什么是服务:服务是Android的四大组件之一,在后台运行

  创建服务

  创建一个继承Service的类,

  其中onBind方法是默认重写的,其他的还有3个重要的方法,onCreate()、onStartCommand()、onDestroy()。​

  1、onCreate()方法会在服务创建的时候调用

  2、onStartCommand()会在每次服务启动的时候调用

  3、onDestroy()会在服务销毁的时候调用。

  每个服务都必须在AndroidManifest.xml中注册才能生效。

  启动和关闭服务

  通过Intent我们可以来开启和关闭服务

  switch (v.getId()){

  case R.id.btn_start:

  Intent startTntent = new Intent(this, MyService.class);

  startService(startTntent);

  break;

  case R.id.btn_stop:

  Intent stopIntent = new Intent(this, MyService.class);

  stopService(stopIntent);

  break;

  default:

  break;

  }

  onBind方法,绑定服务

  private DownloadBinder mBinder = new DownloadBinder();

  class DownloadBinder extends Binder{

  public void startDownload(){

  Log.d("TAG","StartDownload");

  }

  public int getProgress(){

  Log.d("TAG","getProgress executed");

  return 0;

  }

  }

  @Nullable

  @Override

  public IBinder onBind(Intent intent) {

  return mBinder;

  }

  private ServiceConnection connection = newServiceConnection() {

  @Override

  public void onServiceConnected(ComponentName name, IBinder service) {

  downloadBinder = (MyService.DownloadBinder) service;

  downloadBinder.startDownload();

  downloadBinder.getProgress();

  }

  @Override

  public void onServiceDisconnected(ComponentName name) {

  }

  };

  case R.id.btn_bindstart:

  Intent bindIntent = new Intent(this, MyService.class);

  bindService(bindIntent,connection,BIND_AUTO_CREATE);

  break;

  case R.id.btn_bindstop:

  unbindService(connection);

  服务器的生命周期:

  略。

  更多的服务---前台服务

  类似于通知的使用方法,在onCreate代码中构建Notification对象,建立Intent对象,PendingIntent,setLatestEventInfo,接下来是startForeground方法

  public void onCreate() {

  super.onCreate();

  Notification notification = newNotification(R.drawable.ic_launcher,"Notification comes",System.currentTimeMillis());

  Intent notificationIntent = new Intent(this, MainActivity.class);

  PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);

  startForeground(1,notification);

  }

  7. IntentService

  为了避免在主线程中出现耗时逻辑,我们需要使用Android的多线程编程的方法,将耗时逻辑放入线程中进行。

  @Override

  public int onStartCommand(Intent intent, int flags,int startId) {

  new Thread(new Runnable() {

  @Override

  public void run() {

  //处理耗时逻辑

  }

  }).start();

  return super.onStartCommand(intent, flags, startId);

  }

  在耗时逻辑执行完成了之后,如果我们希望服务在处理完这些内容之后就自动关闭,呢么在耗时逻辑的最后加上stopSelf()方法是个不错的选择。

  当然这里要可以使用IntentService类,它可以简单的创建一个异步的,会自动停止的服务。

  public class MyIntentService extends IntentService{

  /**

  * Creates an IntentService. Invoked by your subclass's constructor.

  *

  *

  */

  public MyIntentService() {

  super("MyIntentService");

  }

  @Override

  protected void onHandleIntent(Intent intent) {

  for (int a = 10; a > 0; a--){

  try {

  Thread.sleep(500);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  Log.d("TAG", ""+a);

  }

  }

  @Override

  public void onDestroy() {

  super.onDestroy();

  Log.d("TAG", "onDestroy");

  }

  }

  ase R.id.btn_intentservice:

  Intent intentService = newIntent(this,MyIntentService.class);

  startService(intentService);

  break;

  源文:http://www.embedu.org/column/3456.html

  >>>更多优秀技术博文每日更新 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值