Android之Service通訊-(2)

來源:互聯網
上載者:User

標籤:

一、Service通過IBinder與Activity進行通訊

在Service中進行下載

Service

package chuiyuan.lsj.androidjava.service;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class DownloadService extends Service {    private String TAG ="MainService" ;    public class MyBinder extends Binder{        public DownloadService getService(){            return DownloadService.this;        }    }    public void startDownload() throws InterruptedException{        //可以看出,這裡是在主線程,所以如果真的下載,應該另開一個線程        Toast.makeText(DownloadService.this,"start download:"+Thread.currentThread().getName(),                Toast.LENGTH_LONG).show();        Thread.sleep(2);        Toast.makeText(DownloadService.this, "download end", Toast.LENGTH_LONG).show();    }    //public MyBinder myBinder ;    public DownloadService() {    }    @Override    public void onCreate() {        Log.d(TAG, "onCreate");        super.onCreate();    }    @Override    public void onDestroy() {        Log.d(TAG, "onDestroy");        super.onDestroy();    }    @Override    public boolean onUnbind(Intent intent) {        Log.d(TAG, "onUnbind");        return super.onUnbind(intent);    }    @Override    public IBinder onBind(Intent intent) {        return  new MyBinder();    }}

測試

public class DownloadActivity extends BaseActivity{    private DownloadService downloadService;    private ServiceConnection sc = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            downloadService = ((DownloadService.MyBinder)service).getService();            try{                downloadService.startDownload();            }catch (InterruptedException e){                e.printStackTrace();            }        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    } ;    @Override    protected void findView() {        setContentView(R.layout.activity_download);    }    @Override    protected void initView() {    }    @Override    protected void setOnClickListener() {    }    @Override    public void onClick(View v) {    }    @Override    protected void onStart() {        super.onStart();        Intent bindIntent = new Intent(this, DownloadService.class);        this.bindService(bindIntent, sc, BIND_AUTO_CREATE);    }    @Override    protected void onStop() {        super.onStop();        unbindService(sc);    }}

二、Service通過Broadcast與Activity通訊

Service 

/** * Service通過BroadCast廣播與Activity通訊 * sendBroadcast from Service--->Android System---> * Receive by broadcastReceiver in Activity */public class BroadcastService extends Service {    private String TAG ="BroadcastService" ;    public class MyBinder extends Binder{        public BroadcastService getService(){            return BroadcastService.this;        }    } ;    public void sendServiceBroadcast() throws InterruptedException{        Toast.makeText(BroadcastService.this, "download in thread:"+ Thread.currentThread().getName(),                Toast.LENGTH_SHORT).show();        Intent intent = new Intent() ;        intent.setAction("chuiyuan.lsj.androidjava.service.broadcastservice") ;        intent.putExtra("value", 1000) ;        sendBroadcast(intent);        Toast.makeText(BroadcastService.this, "send over", Toast.LENGTH_LONG).show();    }    public BroadcastService() {    }    @Override    public IBinder onBind(Intent intent) {        return  new MyBinder();    }    @Override    public void onCreate() {        super.onCreate();        //如果 是用的startService,可以在這裡執行//        Toast.makeText(this, "onCreate:send broadcast", Toast.LENGTH_SHORT).show();//        try {//            sendServiceBroadcast();//        }catch (InterruptedException e){//            e.printStackTrace();//        }    }    @Override    public void onDestroy() {        Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();        super.onDestroy();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();        return super.onStartCommand(intent, flags, startId);    }}

測試

public class ServiceSendbroadcastActivity extends BaseActivity{    private BroadcastService broadcastService;    private ServiceConnection sc = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            broadcastService = ((BroadcastService.MyBinder)service).getService();            try{                broadcastService.sendServiceBroadcast();            }catch (InterruptedException e){                e.printStackTrace();            }        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    } ;    @Override    protected void findView() {        setContentView(R.layout.activity_service_sendbroadccast);    }    @Override    protected void initView() {        //廣播註冊        IntentFilter filter = new IntentFilter() ;        filter.addAction("chuiyuan.lsj.androidjava.service.broadcastservice");        registerReceiver(serviceReceiver, filter) ;    }    @Override    protected void setOnClickListener() {    }    @Override    public void onClick(View v) {    }    @Override    protected void onStop() {        super.onStop();        unbindService(sc);    }    @Override    protected void onStart() {        super.onStart();        Intent bindIntent = new Intent(this, BroadcastService.class) ;        bindService(bindIntent, sc, BIND_AUTO_CREATE);    }    public BroadcastReceiver serviceReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            Bundle extras = intent.getExtras() ;            if (extras!= null){                if (extras.containsKey("value")){                    //這裡可以做下載,發包等                    Toast.makeText(ServiceSendbroadcastActivity.this,                            "receive broadcast:"+extras.get("value"), Toast.LENGTH_SHORT).show();                }            }        }    } ;}

  

  

  

  

Android之Service通訊-(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.