方式一: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)傳值。