Service与Activity之间通信


  • 通过Binder对象
    一个service与一个activity之间通信,通常这种情况下,我们使用最多的是通过回调接口。具体做法是在service中定义一个接口,在activity中实现改接口,并通过bindservice来传入。
    首先创建Service:
public class MyService extends Service{ 
    public ServiceBinder mBinder = new ServiceBinder(); 
    /* 数据通信的桥梁 */ 
    /* 重写Binder的onBind函数,返回派生类 */ 
    @Override 
    public IBinder onBind(Intent arg0) {
         return mBinder; 
    } 
    @Override 
    public void onCreate() { 
        Toast.makeText( MyService.this, "Service Create...", Toast.LENGTH_SHORT).show(); 
        super.onCreate(); }
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) {         
        Toast.makeText(MyService.this, "Service StartCommand", Toast.LENGTH_SHORT).show(); 
        return super.onStartCommand(intent, flags, startId); 
    } 
    @Override 
    public void onDestroy() { 
        Toast.makeText( MyService.this, "Service Destroy", Toast.LENGTH_SHORT).show(); 
    } 
    /* 第一种模式通信:Binder */ 
    public class ServiceBinder extends Binder { 
        public void startDownload() throws InterruptedException { 
            /* 模拟下载,休眠2秒 */ 
            Toast.makeText( MyService.this, "模拟下载2秒钟,开始下载...", Toast.LENGTH_SHORT).show(); 
            Thread.sleep(2); 
            Toast.makeText( MyService.this, "下载结束...", Toast.LENGTH_SHORT).show(); 
        } 
     }
}

创建通信的Activity:

public class MainActivity extends AppcompatActivity { 
    /* 通过Binder,实现Activity与Service通信 */ 
    private MyService.ServiceBinder mBinderService; 
    private ServiceConnection connection = new ServiceConnection() {     
        @Override 
        public void onServiceDisconnected(ComponentName name) { 
        } 
        @Override 
        public void onServiceConnected(ComponentName name, IBinder service) { 
            mBinderService = (MyService.ServiceBinder) service; 
            try { 
                mBinderService.startDownload(); 
            } 
            catch (InterruptedException e) { 
                e.printStackTrace(); 
            } 
        } 
    }; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.activity_main); 

        Intent Intent = new Intent(MainActivity.this, MyService.class); 
        bindService(Intent, connection, BIND_AUTO_CREATE); 
    }
    @Override  
    protected void onDestroy() {  
        unbindService(connection);  
        super.onDestroy();  
    }  
}

Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法。


  • Service通过BroadCast广播与Activity通信
    创建发送广播的Service
public class MsgService extends Service {  
   // 进度条的最大值 
  public static final int MAX_PROGRESS = 100;  
    //进度条的进度值 
    private int progress = 0;        
    private Intent intent = new Intent("com.example.communication.RECEIVER");  
     //模拟下载任务,每秒钟更新一次
    public void startDownLoad(){  
        new Thread(new Runnable() {      
            @Override  
            public void run() {  
                while(progress < MAX_PROGRESS){  
                    progress += 5;  
                      
                    //发送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;  
    }    
}

创建接收广播的Activity

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);  
          
        //动态注册广播接收器  
        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) {  
                //启动服务  
                mIntent = new Intent(MainActivity.this, MsgService.class);  
                startService(mIntent);  
            }  
        });  
          
    }  
  
      
    @Override  
    protected void onDestroy() {  
        //停止服务  
        stopService(mIntent);  
        //注销广播  
        unregisterReceiver(msgReceiver);  
        super.onDestroy();  
    }  
  
  
    /** 
     * 广播接收器 
     * @author len 
     * 
     */  
    public class MsgReceiver extends BroadcastReceiver{  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            //拿到进度,更新UI  
            int progress = intent.getIntExtra("progress", 0);  
            mProgressBar.setProgress(progress);  
        }  
          
    }  
  
}  

Service使用广播向Activity发送消息,Activity要注册相应的接收器。当Service要向多个Activity发送同样的消息的话,用广播发送好。


参考:
Service与Activity之间通信

你可能感兴趣的:(Service与Activity之间通信)