2012-08-25 97 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更多