java - Android:无法使用 null 启动服务:java.lang.NullPointerException

标签 java android service nullpointerexception foreground-service

在开始之前,我想澄清一下,我已经阅读了类似主题的先前答案(主要是 this one ),并且即使在评论中给出的答案也不适合我(在 Intent 之前添加 Intent != null .getAction() 不起作用)。

我正在尝试为玛雅星座提供前台服务。该服务的目的是从 SQLite 数据库读取星座符号和预测,每当收到包含以下内容的文本消息:“MAYA dd/MM/yyyy”(DOB)时,该服务就会获取该信息并发送自动一条短信。 我已经让它作为后台服务工作而没有错误,但我想给它一个通知,以便用户可以查看该服务是否正在运行。

我按照其他教程( tutorial 1tutorial 2 )来制作前台服务,它工作正常,没有错误。

我现在的问题是,每当我启动服务、停止服务并最终清除内存(杀死应用程序)时,我总是在服务的第 57 行上收到空指针异常(无论我有什么代码,它总是行57)。 我的手机上显示消息“不幸的是 HoroscopoMaya 已停止工作”。两次!

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".ServicioAstralMaya"
             android:exported="false" />
</application>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

MainActivity.java:

public void startService( View view )
{
    if( bRunning == false )
    {
        Intent intent = new Intent( MainActivity.this, ServicioAstralMaya.class );
        intent.setAction( Constants.ACTION.START_FOREGROUND_ACTION );
        startService( intent );
        txtVStatServ.setText( "INVOCADOS " );
        bRunning = true;
    }
}//END startService( View )

public void stopService( View view )
{
    if( bRunning == true )
    {
        Intent intent = new Intent( MainActivity.this, ServicioAstralMaya.class );
        intent.setAction( Constants.ACTION.STOP_FOREGROUND_ACTION );
        startService( intent );
        txtVStatServ.setText( "DESCANSANDO " );
        bRunning = false;
    }
}//END stopService( View )

ServicioAstralMaya.java(服务):

@Override
public int onStartCommand( Intent intent, int flags, int startID )
{
    if( intent != null && intent.getAction().equals( Constants.ACTION.START_FOREGROUND_ACTION
    ) )
    {
        Log.i( TAG, "Servicio iniciado!" );
        isRunning = true;
        startForeground( Constants.NOTIFICATION_ID.SERVICE_ID, getCompatNotification() );
    }else if( intent != null && intent.getAction().equals( Constants.ACTION.STOP_FOREGROUND_ACTION ) )
    {

        Log.i( TAG, "Servicio detenido!" );
        isRunning = false;
        stopForeground( true );
        stopSelf();
    }
    return START_STICKY;
}

private Notification getCompatNotification()
{
    NotificationCompat.Builder builder = new NotificationCompat.Builder( this );
    builder.setSmallIcon( R.drawable.homonculus_32 )
        .setContentTitle( "Horoscopos Maya" )
        .setTicker( "Astros Conectados" )
        .setWhen( System.currentTimeMillis() );
    Intent startIntent = new Intent( this, MainActivity.class );
    PendingIntent contentIntent = PendingIntent.getActivity( this, 0, startIntent,
        0 );
    builder.setContentIntent( contentIntent );
    Notification notification = builder.build();

    return notification;
}//END Notification getCompatNotification()

@Override
public void onDestroy()
{
    super.onDestroy();
    isRunning = false;
}

常量.java

public interface ACTION
{
    public static final String START_FOREGROUND_ACTION = "edu.ito.jmhg" +
        ".horoscopomaya.action.START_FOREGROUND";
    public static final String STOP_FOREGROUND_ACTION = "edu.ito.jmhg" +
        ".horoscopomaya.action.STOP_FOREGROUND";
}

public interface NOTIFICATION_ID
{
    public static final int SERVICE_ID = 1;
}

第 57 行是这样的:Log.i( TAG, "Servicio iniciado!");

isRunning和bRunning是检查服务是否正在运行,以便在MainActivity中显示状态:

bRunning = isServiceRunning( ServicioAstralMaya.class );

private boolean isServiceRunning( Class<?> serviceClass )
{
    ActivityManager manager = (ActivityManager)getSystemService( Context.ACTIVITY_SERVICE );
    for( ActivityManager.RunningServiceInfo service : manager.getRunningServices( Integer
        .MAX_VALUE ) )
    {
        if( serviceClass.getName().equals( service.service.getClassName() ) ) {
            return true;
        }
    }
    return false;
}//END boolean isServiceRunning( Class<?> )

并在服务中:public static boolean isRunning;

我什至尝试调用 stopService 并在 onDestroy() 方法中执行 stopForeground(true);stopSelf();但仍然无济于事。错误仍然是我的服务类的第 57 行。

日志猫:

FATAL EXCEPTION: main
Process: edu.ito.jmhg.horoscopomaya, PID: 21642
java.lang.RuntimeException: Unable to start service  edu.ito.jmhg.horoscopomaya.ServicioAstralMaya@426d11c8 with null: java.lang.NullPointerException
...
Caused by: java.lang.NullPointerException at edu.ito.jmhg.horoscopomaya.ServicioAstralMaya.onStartCommand(ServicioAstralMaya.java:57)

我正在使用已 root 的 Samsung Grand Prime 和 Android Studio 2 运行 Android KitKat 4.4.4 (API 19)。

编辑

我不知道这是否有些相关,但我确实注意到了有关 Android Studio 的一些事情。 无论我进行什么更改,当我运行应用程序时,我都会收到“没有要部署的更改”的通知

事件日志:

19:32:47 Executing tasks: [:app:assembleDebug]
19:33:50 Gradle build finished in 1m 3s 59ms
19:33:51 No changes to deploy

我更改了服务代码,行错误仍然是 57,现在是 ) ) 紧接在 if(intent.getAction().equals( Constants.ACTION) 之后.START_FOREGROUND_ACTION

ServicioAstralMaya.java(服务):

@Override
public int onStartCommand( Intent intent, int flags, int startID )
{
    if( intent != null && intent.getAction() != null )
    {
        if( intent.getAction().equals( Constants.ACTION.START_FOREGROUND_ACTION
        ) )
        {
            Log.i( TAG, "Servicio iniciado!" );
            isRunning = true;
            startForeground( Constants.NOTIFICATION_ID.SERVICE_ID, getCompatNotification() );
        }else if( intent.getAction().equals( Constants.ACTION.STOP_FOREGROUND_ACTION ) )
        {
            Log.i( TAG, "Servicio detenido!" );
            isRunning = false;
            stopForeground( true );
            stopSelf();
        }
    }
    return START_STICKY;
}

此外,由于我已更改为 Android 2,所以我的 gradle 已更新,并且出现了一个奇怪的错误,我必须将 build.gradle 中的 buildToolsVersion 从 buildToolsVersion "24.0 rc2" 更改为 buildTools版本“23.0.2”

构建.gradle:

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "edu.ito.jmhg.horoscopomaya"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
}

最佳答案

问题出在 Android Studio 本身!!

就像我在编辑中所说的那样,Android Studio 给了我“没有要部署的更改”,这很奇怪,所以我搜索了它并发现 this solution

Just go to "File -> Settings -> Build, Execution, Deployement -> Instant Run" and just disable it. With this Android Studio builds from scratch each time but it's better than not building it right.

为了安全起见,我保留了 @Francesc 提到的 if 条件,并且我的应用程序不再给我 NullPointerException 了。

关于java - Android:无法使用 null 启动服务:java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830148/

相关文章:

Java 光滑;延迟后运行命令而不循环;

java - 尝试启动 Firebase Java 客户端

android - 你如何命名 UI 元素?

service - 在 liferay 主题(速度模板)中使用自定义服务或 liferay 服务?

delphi - 服务无法访问文件夹

android - 7.0及以上版本应用被杀后重启服务

java - 如何在使用 JAVA 和 Cucumber 进行测试的每个步骤后捕获屏幕截图?

java - AudioRecord PCM数据有没有用?

android - 什么时候必须手动停止服务?

Android:测试运行失败:由于 'java.lang.IncompatibleClassChangeError',仪器运行失败