最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Android Service與Activity之間通信的幾種方式

 更新時(shí)間:2018年04月02日 12:08:03   作者:xiaanming  
這篇文章主要介紹了詳解Android Service與Activity之間通信的幾種方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

在Android中,Activity主要負(fù)責(zé)前臺(tái)頁面的展示,Service主要負(fù)責(zé)需要長期運(yùn)行的任務(wù),所以在我們實(shí)際開發(fā)中,就會(huì)常常遇到Activity與Service之間的通信,我們一般在Activity中啟動(dòng)后臺(tái)Service,通過Intent來啟動(dòng),Intent中我們可以傳遞數(shù)據(jù)給Service,而當(dāng)我們Service執(zhí)行某些操作之后想要更新UI線程,我們應(yīng)該怎么做呢?接下來我就介紹兩種方式來實(shí)現(xiàn)Service與Activity之間的通信問題

通過Binder對(duì)象

當(dāng)Activity通過調(diào)用bindService(Intent service, ServiceConnection conn,int flags),我們可以得到一個(gè)Service的一個(gè)對(duì)象實(shí)例,然后我們就可以訪問Service中的方法,我們還是通過一個(gè)例子來理解一下吧,一個(gè)模擬下載的小例子,帶大家理解一下通過Binder通信的方式

首先我們新建一個(gè)工程Communication,然后新建一個(gè)Service類

package com.example.communication; 
import android.app.Service; 
import android.content.Intent; 
import android.os.Binder; 
import android.os.IBinder; 
public class MsgService extends Service { 
  /** 
   * 進(jìn)度條的最大值 
   */ 
  public static final int MAX_PROGRESS = 100; 
  /** 
   * 進(jìn)度條的進(jìn)度值 
   */ 
  private int progress = 0; 
 
  /** 
   * 增加get()方法,供Activity調(diào)用 
   * @return 下載進(jìn)度 
   */ 
  public int getProgress() { 
    return progress; 
  } 
 
  /** 
   * 模擬下載任務(wù),每秒鐘更新一次 
   */ 
  public void startDownLoad(){ 
    new Thread(new Runnable() { 
       
      @Override 
      public void run() { 
        while(progress < MAX_PROGRESS){ 
          progress += 5; 
          try { 
            Thread.sleep(1000); 
          } catch (InterruptedException e) { 
            e.printStackTrace(); 
          } 
           
        } 
      } 
    }).start(); 
  } 
  
  /** 
   * 返回一個(gè)Binder對(duì)象 
   */ 
  @Override 
  public IBinder onBind(Intent intent) { 
    return new MsgBinder(); 
  }    
  public class MsgBinder extends Binder{ 
    /** 
     * 獲取當(dāng)前Service的實(shí)例 
     * @return 
     */ 
    public MsgService getService(){ 
      return MsgService.this; 
    } 
  }  
} 

上面的代碼比較簡單,注釋也比較詳細(xì),最基本的Service的應(yīng)用了,相信你看得懂的,我們調(diào)用startDownLoad()方法來模擬下載任務(wù),然后每秒更新一次進(jìn)度,但這是在后臺(tái)進(jìn)行中,我們是看不到的,所以有時(shí)候我們需要他能在前臺(tái)顯示下載的進(jìn)度問題,所以我們接下來就用到Activity了

Intent intent = new Intent("com.example.communication.MSG_ACTION");  
bindService(intent, conn, Context.BIND_AUTO_CREATE); 

通過上面的代碼我們就在Activity綁定了一個(gè)Service,上面需要一個(gè)ServiceConnection對(duì)象,它是一個(gè)接口,我們這里使用了匿名內(nèi)部類

ServiceConnection conn = new ServiceConnection() { 
     
    @Override 
    public void onServiceDisconnected(ComponentName name) { 
       
    } 
     
    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
      //返回一個(gè)MsgService對(duì)象 
      msgService = ((MsgService.MsgBinder)service).getService(); 
       
    } 
  };

在onServiceConnected(ComponentName name, IBinder service) 回調(diào)方法中,返回了一個(gè)MsgService中的Binder對(duì)象,我們可以通過getService()方法來得到一個(gè)MsgService對(duì)象,然后可以調(diào)用MsgService中的一些方法,Activity的代碼如下

package com.example.communication;  
import android.app.Activity; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ProgressBar;  
public class MainActivity extends Activity { 
  private MsgService msgService; 
  private int progress = 0; 
  private ProgressBar mProgressBar; 
   
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);      
    //綁定Service 
    Intent intent = new Intent("com.example.communication.MSG_ACTION"); 
    bindService(intent, conn, Context.BIND_AUTO_CREATE);      
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1); 
    Button mButton = (Button) findViewById(R.id.button1); 
    mButton.setOnClickListener(new OnClickListener() {        
      @Override 
      public void onClick(View v) { 
        //開始下載 
        msgService.startDownLoad(); 
        //監(jiān)聽進(jìn)度 
        listenProgress(); 
      } 
    }); 
     
  } 
   
 
  /** 
   * 監(jiān)聽進(jìn)度,每秒鐘獲取調(diào)用MsgService的getProgress()方法來獲取進(jìn)度,更新UI 
   */ 
  public void listenProgress(){ 
    new Thread(new Runnable() {        
      @Override 
      public void run() { 
        while(progress < MsgService.MAX_PROGRESS){ 
          progress = msgService.getProgress(); 
          mProgressBar.setProgress(progress); 
          try { 
            Thread.sleep(1000); 
          } catch (InterruptedException e) { 
            e.printStackTrace(); 
          } 
        }          
      } 
    }).start(); 
  }    
  ServiceConnection conn = new ServiceConnection() { 
    @Override 
    public void onServiceDisconnected(ComponentName name) { 
       
    } 
     
    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
      //返回一個(gè)MsgService對(duì)象 
      msgService = ((MsgService.MsgBinder)service).getService();        
    } 
  }; 
 
  @Override 
  protected void onDestroy() { 
    unbindService(conn); 
    super.onDestroy(); 
  }  
}

其實(shí)上面的代碼我還是有點(diǎn)疑問,就是監(jiān)聽進(jìn)度變化的那個(gè)方法我是直接在線程中更新UI的,不是說不能在其他線程更新UI操作嗎,可能是ProgressBar比較特殊吧,我也沒去研究它的源碼,知道的朋友可以告訴我一聲,謝謝!

上面的代碼就完成了在Service更新UI的操作,可是你發(fā)現(xiàn)了沒有,我們每次都要主動(dòng)調(diào)用getProgress()來獲取進(jìn)度值,然后隔一秒在調(diào)用一次getProgress()方法,你會(huì)不會(huì)覺得很被動(dòng)呢?可不可以有一種方法當(dāng)Service中進(jìn)度發(fā)生變化主動(dòng)通知Activity,答案是肯定的,我們可以利用回調(diào)接口實(shí)現(xiàn)Service的主動(dòng)通知,不理解回調(diào)方法的可以看看http://m.fzitv.net/article/112637.htm

新建一個(gè)回調(diào)接口

public interface OnProgressListener { 
  void onProgress(int progress); 
} 

MsgService的代碼有一些小小的改變,為了方便大家看懂,我還是將所有代碼貼出來

package com.example.communication;  
import android.app.Service; 
import android.content.Intent; 
import android.os.Binder; 
import android.os.IBinder;  
public class MsgService extends Service { 
  /** 
   * 進(jìn)度條的最大值 
   */ 
  public static final int MAX_PROGRESS = 100; 
  /** 
   * 進(jìn)度條的進(jìn)度值 
   */ 
  private int progress = 0; 
   
  /** 
   * 更新進(jìn)度的回調(diào)接口 
   */ 
  private OnProgressListener onProgressListener; 
      
  /** 
   * 注冊(cè)回調(diào)接口的方法,供外部調(diào)用 
   * @param onProgressListener 
   */ 
  public void setOnProgressListener(OnProgressListener onProgressListener) { 
    this.onProgressListener = onProgressListener; 
  } 
 
  /** 
   * 增加get()方法,供Activity調(diào)用 
   * @return 下載進(jìn)度 
   */ 
  public int getProgress() { 
    return progress; 
  } 
 
  /** 
   * 模擬下載任務(wù),每秒鐘更新一次 
   */ 
  public void startDownLoad(){ 
    new Thread(new Runnable() {        
      @Override 
      public void run() { 
        while(progress < MAX_PROGRESS){ 
          progress += 5; 
           
          //進(jìn)度發(fā)生變化通知調(diào)用方 
          if(onProgressListener != null){ 
            onProgressListener.onProgress(progress); 
          } 
           
          try { 
            Thread.sleep(1000); 
          } catch (InterruptedException e) { 
            e.printStackTrace(); 
          }            
        } 
      } 
    }).start(); 
  } 
  
  /** 
   * 返回一個(gè)Binder對(duì)象 
   */ 
  @Override 
  public IBinder onBind(Intent intent) { 
    return new MsgBinder(); 
  }    
  public class MsgBinder extends Binder{ 
    /** 
     * 獲取當(dāng)前Service的實(shí)例 
     * @return 
     */ 
    public MsgService getService(){ 
      return MsgService.this; 
    } 
  }  
}

Activity中的代碼如下

package com.example.communication;  
import android.app.Activity; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ProgressBar;  
public class MainActivity extends Activity { 
  private MsgService msgService; 
  private ProgressBar mProgressBar; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);       
    //綁定Service 
    Intent intent = new Intent("com.example.communication.MSG_ACTION"); 
    bindService(intent, conn, Context.BIND_AUTO_CREATE);      
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1); 
    Button mButton = (Button) findViewById(R.id.button1); 
    mButton.setOnClickListener(new OnClickListener() { 
       
      @Override 
      public void onClick(View v) { 
        //開始下載 
        msgService.startDownLoad(); 
      } 
    }); 
     
  } 
   
 
  ServiceConnection conn = new ServiceConnection() { 
    @Override 
    public void onServiceDisconnected(ComponentName name) { 
       
    } 
     
    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
      //返回一個(gè)MsgService對(duì)象 
      msgService = ((MsgService.MsgBinder)service).getService();        
      //注冊(cè)回調(diào)接口來接收下載進(jìn)度的變化 
      msgService.setOnProgressListener(new OnProgressListener() {          
        @Override 
        public void onProgress(int progress) { 
          mProgressBar.setProgress(progress);            
        } 
      });        
    } 
  }; 
 
  @Override 
  protected void onDestroy() { 
    unbindService(conn); 
    super.onDestroy(); 
  }  
} 

用回調(diào)接口是不是更加的方便呢,當(dāng)進(jìn)度發(fā)生變化的時(shí)候Service主動(dòng)通知Activity,Activity就可以更新UI操作了

通過broadcast(廣播)的形式

當(dāng)我們的進(jìn)度發(fā)生變化的時(shí)候我們發(fā)送一條廣播,然后在Activity的注冊(cè)廣播接收器,接收到廣播之后更新ProgressBar,代碼如下

package com.example.communication; 
import android.app.Activity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ProgressBar;  
public class MainActivity extends Activity { 
  private ProgressBar mProgressBar; 
  private Intent mIntent; 
  private MsgReceiver msgReceiver; 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
     
    //動(dòng)態(tài)注冊(cè)廣播接收器 
    msgReceiver = new MsgReceiver(); 
    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction("com.example.communication.RECEIVER"); 
    registerReceiver(msgReceiver, intentFilter); 
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1); 
    Button mButton = (Button) findViewById(R.id.button1); 
    mButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        //啟動(dòng)服務(wù) 
        mIntent = new Intent("com.example.communication.MSG_ACTION"); 
        startService(mIntent); 
      } 
    }); 
     
  } 

  @Override 
  protected void onDestroy() { 
    //停止服務(wù) 
    stopService(mIntent); 
    //注銷廣播 
    unregisterReceiver(msgReceiver); 
    super.onDestroy(); 
  } 
 
  /** 
   * 廣播接收器 
   * @author len 
   * 
   */ 
  public class MsgReceiver extends BroadcastReceiver{  
    @Override 
    public void onReceive(Context context, Intent intent) { 
      //拿到進(jìn)度,更新UI 
      int progress = intent.getIntExtra("progress", 0); 
      mProgressBar.setProgress(progress); 
    } 
   }  
} 
package com.example.communication;  
import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder;  
public class MsgService extends Service { 
  /** 
   * 進(jìn)度條的最大值 
   */ 
  public static final int MAX_PROGRESS = 100; 
  /** 
   * 進(jìn)度條的進(jìn)度值 
   */ 
  private int progress = 0;    
  private Intent intent = new Intent("com.example.communication.RECEIVER"); 
   
 
  /** 
   * 模擬下載任務(wù),每秒鐘更新一次 
   */ 
  public void startDownLoad(){ 
    new Thread(new Runnable() { 
      @Override 
      public void run() { 
        while(progress < MAX_PROGRESS){ 
          progress += 5;            
          //發(fā)送Action為com.example.communication.RECEIVER的廣播 
          intent.putExtra("progress", progress); 
          sendBroadcast(intent);            
          try { 
            Thread.sleep(1000); 
          } catch (InterruptedException e) { 
            e.printStackTrace(); 
          }            
        } 
      } 
    }).start(); 
  } 

  @Override 
  public int onStartCommand(Intent intent, int flags, int startId) { 
    startDownLoad(); 
    return super.onStartCommand(intent, flags, startId); 
  } 
 
  @Override 
  public IBinder onBind(Intent intent) { 
    return null; 
  }  
}

總結(jié):

Activity調(diào)用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service對(duì)象的一個(gè)引用,這樣Activity可以直接調(diào)用到Service中的方法,如果要主動(dòng)通知Activity,我們可以利用回調(diào)方法

Service向Activity發(fā)送消息,可以使用廣播,當(dāng)然Activity要注冊(cè)相應(yīng)的接收器。比如Service要向多個(gè)Activity發(fā)送同樣的消息的話,用這種方法就更好

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • android studio無法添加 bmob sdk依賴問題及解決方法

    android studio無法添加 bmob sdk依賴問題及解決方法

    這篇文章主要介紹了android studio無法添加 bmob sdk依賴,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Android Flutter實(shí)現(xiàn)五種酷炫文字動(dòng)畫效果詳解

    Android Flutter實(shí)現(xiàn)五種酷炫文字動(dòng)畫效果詳解

    animated_text_kit這一動(dòng)畫庫有多種文字動(dòng)畫效果,文中將利用它實(shí)現(xiàn)五種酷炫的文字動(dòng)畫:波浪涌動(dòng)效果、波浪線跳動(dòng)文字組、彩虹動(dòng)效、滾動(dòng)廣告牌效果和打字效果,需要的可以參考一下
    2022-03-03
  • Android中判斷網(wǎng)絡(luò)連接狀態(tài)的方法

    Android中判斷網(wǎng)絡(luò)連接狀態(tài)的方法

    App判斷用戶是否聯(lián)網(wǎng)是很普遍的需求,這篇文章主要介紹了Android中判斷網(wǎng)絡(luò)連接狀態(tài)的方法,感興趣的朋友可以參考一下
    2016-02-02
  • Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法

    Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法

    android 讀取json數(shù)據(jù),下面小編給大家整理有關(guān)Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法,需要的朋友可以參考下
    2015-08-08
  • Android?Gradle?三方依賴管理詳解

    Android?Gradle?三方依賴管理詳解

    這篇文章主要介紹了Android?Gradle?三方依賴管理詳解,Gradle的依賴管理是一個(gè)從開始接觸Android開發(fā)就一直伴隨著我們的問題,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-08-08
  • Android 源碼如何編譯調(diào)試

    Android 源碼如何編譯調(diào)試

    本文主要介紹Android 源碼編譯調(diào)試,這里對(duì)Android 源碼的編譯以及調(diào)試做了詳細(xì)的流程詳解,有需要的小伙伴可以參考下
    2016-08-08
  • Android使用xUtils3.0實(shí)現(xiàn)文件上傳

    Android使用xUtils3.0實(shí)現(xiàn)文件上傳

    這篇文章主要為大家詳細(xì)介紹了Android使用xUtils3.0實(shí)現(xiàn)文件上傳的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • Android JetpackCompose使用教程講解

    Android JetpackCompose使用教程講解

    在今年的Google/IO大會(huì)上,亮相了一個(gè)全新的 Android 原生 UI 開發(fā)框架-Jetpack Compose, 與蘋果的SwiftIUI一樣,Jetpack Compose是一個(gè)聲明式的UI框架
    2022-10-10
  • Android Studio實(shí)現(xiàn)發(fā)短信功能

    Android Studio實(shí)現(xiàn)發(fā)短信功能

    這篇文章主要介紹了Android Studio實(shí)現(xiàn)發(fā)短信功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-06-06
  • Android實(shí)現(xiàn)帶有記住密碼功能的登陸界面

    Android實(shí)現(xiàn)帶有記住密碼功能的登陸界面

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)帶有記住密碼功能的登陸界面,主要采用SharedPreferences來保存用戶數(shù)據(jù),感興趣的小伙伴們可以參考一下
    2016-05-05

最新評(píng)論

丰原市| 连平县| 永宁县| 普洱| 宣威市| 司法| 搜索| 澜沧| 股票| 嵊州市| 仙桃市| 黄大仙区| 武城县| 涞水县| 深泽县| 望江县| 黄平县| 西宁市| 阿克陶县| 阿拉尔市| 瑞丽市| 始兴县| 咸宁市| 和平县| 庄河市| 叙永县| 磐石市| 新民市| 怀化市| 新野县| 唐海县| 桃源县| 开平市| 深水埗区| 盐边县| 博野县| 广东省| 淮南市| 长海县| 西平县| 楚雄市|