Android服务无法启动Intent和NullPointerException

mga*_*lal 1 service android

我正在创建后台服务(在其自己的过程中),并且使其无法正常工作。我正在尝试在应用程序启动时启动它,并且在日志中显示由于意图错误而无法启动服务。我一直在浏览论坛,示例(和Google),但找不到我做错的事情。

这是我得到的错误:
E / AndroidRuntime(1398):java.lang.RuntimeException:无法使用意图{cmp = xxxx}启动服务com.test.alarms.AlarmService@41550cb0:java.lang.NullPointerException

在活动中,我有:

startService(new Intent(AlarmService.class.getName()));
Run Code Online (Sandbox Code Playgroud)

服务类别为:

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);
}
Run Code Online (Sandbox Code Playgroud)

}

清单文件具有:

<service
        android:name=".AlarmService"
        android:process=":remote">
        <intent-filter>
            <action android:name="com.test.alarms.AlarmService"/>
        </intent-filter>
    </service>
Run Code Online (Sandbox Code Playgroud)

谢谢,

nan*_*esh 5

也许问题是您已经重写了OnCreate和OnDestroy,但是您没有调用super.Oncreate()和super.onDestroy()。

如果这不起作用,请尝试

startService(new Intent(context , AlarmService.class));
Run Code Online (Sandbox Code Playgroud)

编辑:也在onStart中使用它

Intent i = new Intent(this, StartActivity.class);
Run Code Online (Sandbox Code Playgroud)

代替

Intent i = new Intent(context, StartActivity.class);
Run Code Online (Sandbox Code Playgroud)


Saz*_*han 5

根据文档,您需要检查 onStartCommand(Intent Intent,int,int); 内部传递的 Intent 是否为 null(用于在进程终止后重新启动)或不是(正常操作);

更好的设计,

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;
}
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多内容