2011-08-20 39 views
1

我熟悉使用putExtra和getExtra方法將數組從一個活動傳遞到另一個活動的方法。然而,每當我試圖從服務中獲得它下面的代碼不起作用:從活動傳遞字符串到服務?

Bundle b = this.getIntent().getExtras(); 
String Array = b.getStringArray("paths"); 

它不能識別以下內容:

this.getIntent().getExtras(); 

任何想法?

編輯

在活動課,我有以下:

toService = new Intent(); 
    toService.setClass(this, Service.class); 
    toService.putExtra("paths",Array); 
服務類

:由於路徑

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 
    Bundle extras = intent.getExtras(); 
    if(extras!=null) 
    { 
     Paths = extras.getStringArray("paths"); 
     Toast.makeText(protectionService.this, Paths[0], Toast.LENGTH_SHORT).show(); 
    } 

    return 0; 
} 

沒有什麼是出現沒有被明顯地分配。

Paths = extras.getStringArray("paths"); 

似乎沒有工作。

+0

你是什麼意思'不起作用'?它會崩潰,給出錯誤的結果等 – Ronnie

+0

我的意思是服務類不承認代碼 this.getIntent()... – Batzi

回答

1

你在哪裏試圖訪問getIntent?

這裏是我寫它使用getExtras的程序片段:

@Override 
public void onStart(Intent intent, int startId) { 
    super.onStart(intent, startId); 
    Bundle extras = intent.getExtras(); 
    if (extras != null) { 
     // Do what you want 
     } 
} 

然而,在onStart現在已經過時,所以你應該使用onStartCommand。 您將意圖作爲參數之一。

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    handleCommand(intent); 
    // We want this service to continue running until it is explicitly 
    // stopped, so return sticky. 
    return START_STICKY; 
} 

否則,你可以使用AIDL,偏好或其他例子也回答這裏:How to access a variable present in a service

同樣的問題已經回答Android: how to get the intent received by a service?

編輯: 如果使用此

toService = new Intent(); 
toService.setClass(this, Service.class); 
toService.putExtra("array",Array); 

您需要使用相同的密鑰獲取額外密鑰,這裏的密鑰是「array」

Paths = extras.getStringArray("array"); 
+0

我編輯了第一篇文章。所以基本上如果extras不等於null,那麼我可以使用extras.getStringArray(「數組」),因爲它在一個活動中使用? – Batzi

+0

是的,你不需要任何getIntent(),因爲你的意圖是onStartCommand中的一個參數。所以在onStartCommand中只需要使用intent.getExtras()。您應該檢查它們是否爲空 –

+0

我已在原始文章中添加了我的代碼的另一部分,請查看它。 Paths = extras.getStringArray(「paths」);不管用。 – Batzi

相關問題