【问题标题】:Android: Unable to start service with null: java.lang.NullPointerExceptionAndroid:无法使用 null 启动服务:java.lang.NullPointerException
【发布时间】:2016-04-24 23:40:10
【问题描述】:

在开始之前,我想澄清一下,我已经阅读过类似主题的先前答案(主要是 this one),即使在 cmets 中给出的答案也对我不起作用(在意图之前添加意图!= null .getAction() 不起作用)。

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

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

我现在的问题是,每当我启动服务、停止服务并最终清除 ram(杀死应用程序)时,我都会在服务的第 57 行收到 Nullpointer 异常(无论我有什么代码,它总是一行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 行。

Logcat:

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)

我正在使用根植于三星 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" 更改为 buildToolsVersion "23.0.2"

build.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'
}

【问题讨论】:

  • 我能看到的唯一可以为null的是getAction()的返回。检查是否为空。
  • 我刚刚试过了,还是没有...
  • 你的服务中的第 57 行是什么?
  • 刚刚编辑显示第 57 行当前有什么

标签: java android service nullpointerexception foreground-service


【解决方案1】:

问题出在 Android Studio 本身!!

就像我在编辑中说的那样,Android Studio 给了我“No changes to deploy”,这很奇怪,所以我搜索了一下,发现this solution

只需转到“文件 -> 设置 -> 构建、执行、部署 -> 即时运行”并禁用它。使用此 Android Studio 构建 每次都从头开始,但总比不正确构建要好。

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

【讨论】:

    【解决方案2】:

    jmhg92 解决方案确实在即时运行处于活动状态时通过服务、模型和片段解决了我的 NullPointerExceptions

    只需转到“文件 -> 设置 -> 构建、执行、部署 -> 即时运行”

    但是,如果您想保留 Instant Run,您可以取消选中“Restart Activity on Code Changes”

    Preferences > Build, Execution, Deployment > Instant Run > 取消选中“Restart Activity on Code Changes”

    到目前为止,我已经能够使用 Instant Run 并且没有收到任何异常。

    希望这个解决方案对某人有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多