2012-04-16 57 views

回答

2

你必須在你的service.OnStart方法中覆蓋onStart方法,你可以獲得Activity的意圖。 如果你想從活動傳遞ArrayList到服務,你可以將你的ArrayList轉換爲數組。

在你活動

Intent intent=new Intent(ServicesActivity.this,FileManagerRequest.class);   
Bundle b=new Bundle() 
b.putStringArray("Array", your_array) 
intent.putExtras(b); 
startService(intent); 

在您服務

public void onStart(Intent intent, int startid){ 
    super.onStart(intent, startid); 
    Bundle b=intent.getExtras(); 
    String[] Array = b.getStringArray("Array"); 
} 
0

兩個選項:

  1. 如果服務是本地的,那麼你就可以綁定到它,只是直接調用方法
  2. 如果服務是遠程的,比你能使用Bundle來傳遞一些數據。
0

/**在您的活動 *** /

startbtn.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Bundle b=new Bundle(); 
      b.putString("id", id); 
      Intent in=new Intent(create.this,myservice.class); 

      in.putExtras(b); 
      //Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_LONG).show(); 
      startService(in); 
} 
0

/**在服務* ***/

public int onStartCommand(Intent intent, int flags, int startId) { 
// We want this service to continue running until it is explicitly 
// stopped, so return sticky. 
     super.onStart(intent, startId); 
    id=intent.getExtras(); 
    value=id.getString("id"); 

Toast.makeText(this, "Service Started "+value, Toast.LENGTH_LONG).show(); 
0

最後我得到了答案,它爲我的工作,只是嘗試。

1)在發送對象喜歡ArrayList<String> names從Activity發送到這種方式的例子。 names.add("kdblue");

Intent startIntent = new Intent(CuurentActivity.this, UploadService.class); 
startIntent.putStringArrayListExtra("data",names); 
startService(startIntent); 

2)現在從服務接收此ArrayList<String>對象

@Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     ArrayList<String> transferData = intent.getStringArrayListExtra("data"); 
     return START_STICKY; 
    } 

注:transferData對象包含所有ArrayList<String> names屬性。

相關問題