2013-04-16 36 views
5

我有下面的代碼意圖總是空onStartCommand

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    if(intent != null) { 
     Log.i("INTENT", intent.getAction().toString()); 
    } 
    return START_STICKY; 
} 

但它總是在線返回NullPointerException

Log.i("INTENT", intent.getAction().toString()); 

爲什麼?我在上面檢查「intent」變量是否爲空。如果是這種情況,請執行以下代碼。但是我仍然得到了零點錯誤。

服務從活動開始這樣的:

startService(new Intent(this, MainService.class)); 

我在做什麼錯?

+0

可能的getAction()返回null

你應該延長您的支票本。嘗試在字符串中檢查它。 類似於'String s = intent.getAction()。toString();'並檢查它是否爲null。 – Wamasa

+0

因爲我也有廣播開始這項服務,我想區分活動開始的服務或廣播開始的服務。 –

+0

@Wamasa我試過了。它仍然返回nullpointerexception。如果我刪除getAction(),服務啓動沒問題。 Wtf? –

回答

12

您正在收到NullPointerException,因爲intent.getAction()似乎要返回null。如果你想一個動作添加到您的意圖,你需要調用setAction()

if(intent != null && intent.getAction() != null) { 

Intent i = new Intent(this, MainService.class); 
i.setAction("foo"); 
startService(i); 
+0

你的男人。它正在工作。我需要延長我的「如果」檢查。 –