Android activity與service傳遞資料
阿新 • • 發佈:2019-02-09
方式一:Activity向Service傳遞資料
在activity中,設定要傳遞的值。
Intent intent = new Intent(Main.this, DownloadService.class);
intent.putExtra("apkUrl", apkUrl);
startService(intent);
然後在service中的onStart()函式中獲取該值
@Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); apkUrl = intent.getStringExtra("apkUrl"); }
我們需要在Mainfeist檔案中註冊這個service
銷燬Service寫在activity的onDestroy()方法裡:
protected void onDestroy() {
Main.this.stopService(new Intent(Main.this, DownloadService.class));
super.onDestroy();
}
補充:
也可以從public int onStartCommand(Intent intent, int flags, intstartId)中取出從activity中傳過來的值。intent.getExtra()獲得bundle物件,可從中取值。
也可以用bindService(intent,conn,BIND_AUTO_CREATE);傳值,把要傳的值繫結在intent裡,在service的public IBinderonBind(Intent intent) 方法裡取得intent。
可以在service裡面註冊一個廣播,在activity裡sendbroadcast(intent)傳值。