Android 服务无法启动 Intent 和 NullPointerException

标签 android service

我正在创建一个后台服务(在它自己的进程中)并且在让它工作时遇到了很多麻烦。我试图在应用程序启动时启动它,但我在日志中收到无法启动服务并出现 Intent 错误。我一直在浏览论坛、示例(和谷歌),但找不到我做错了什么。

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

在我的 Activity 中:

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);
}

list 文件有:

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

谢谢,

最佳答案

也许问题是您覆盖了 OnCreate 和 OnDestroy,但您没有调用 super.Oncreate() 和 super.onDestroy()。

如果不行试试

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

编辑: 也可以在 onStart 中使用它

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

代替

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

关于Android 服务无法启动 Intent 和 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12124440/

相关文章:

Android OnClickListener 没有触发单独布局上的按钮

android - 获取从中膨胀 View 的资源 ID

android - 在 Oreo 启动时启动后台服务

azure - 为什么从门户更新部署后云服务的IP地址会改变

c# - Http 服务器 - 监听响应

android - 如何防止自定义家庭启动器应用重启 Activity ?

java - 如何简化尴尬的并发代码?

android - 在 Android 中按比例调整 ImageView 的大小

ruby-on-rails - 检查服务/API 的内容是否已过期 - 优化/缓存服务使用的最佳实践?

service - Systemd - 如果服务停止超过 X 次,则始终运行服务并重新启动