2012-08-25 110 views
0

我正在創建一個後臺服務(在它自己的進程中),並且在啓動它時遇到了很多麻煩。我試圖在應用程序啓動時啓動它,並且在日誌中出現intent錯誤時無法啓動服務。我一直在通過論壇,例子(和谷歌),並找不到我做錯了什麼。Android服務無法啓動intent&NullPointerException

這是我得到的錯誤:
E/AndroidRuntime(1398):了java.lang.RuntimeException:無法啓動意圖服務[email protected] {CMP = XXXX}:JAVA .lang.NullPointerException

在活動中,我有:

startService(new Intent(AlarmService.class.getName())); 

服務類是:

package com.test.alarms; 


public class AlarmService extends Service{ 

Context context; 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onCreate() { 
//code to execute when the service is first created 
} 

@Override 
public void onDestroy() { 
//code to execute when the service is shutting down 
} 

@Override 
public void onStart(Intent intent, int startid) { 
//code to execute when the service is starting up 
    Intent i = new Intent(context, StartActivity.class); 
    PendingIntent detailsIntent = PendingIntent.getActivity(this, 0, i, 0); 

    NotificationManager notificationSingleLine = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    Notification notificationDropText = new Notification(R.drawable.ic_launcher, "Alarm for...", System.currentTimeMillis()); 

    CharSequence from = "Time for..."; 
    CharSequence message = "Alarm Text";   
    notificationDropText.setLatestEventInfo(this, from, message, detailsIntent); 

    notificationDropText.vibrate = new long[] { 100, 250, 100, 500};   
    notificationSingleLine.notify(0, notificationDropText); 
} 

}

清單文件有:

<service 
     android:name=".AlarmService" 
     android:process=":remote"> 
     <intent-filter> 
      <action android:name="com.test.alarms.AlarmService"/> 
     </intent-filter> 
    </service> 

感謝,

回答

4

也許這個問題是你有重寫OnCreate中和的OnDestroy,但你是不是調用super.Oncreate()和super.onDestroy()。

如果這不起作用嘗試

startService(new Intent(context , AlarmService.class)); 

編輯: 處理通信,還可以使用此

Intent i = new Intent(this, StartActivity.class); 

,而不是

Intent i = new Intent(context, StartActivity.class); 
+0

謝謝,但我仍然得到錯誤 – mgalal

+0

你得到什麼錯誤?還檢查我的編輯 – nandeesh

+0

E/AndroidRuntime(1398):java.lang.RuntimeException:無法啓動服務[email protected]與意圖{cmp = xxxx}:java.lang.NullPointerException – mgalal

2

Acording到documentation,你需要檢查是否傳遞意圖爲空(用於在進程終止後重新啓動) (正常操作)onStartCommand(Intent intent,int,int);

更好的設計,

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

閱讀here更多