Service crashes with nullpointerexception at onCre

2020-05-02 03:23发布

问题:

i wanted to check the actual time every 5 mins in a service and mute or unmute the phone depending on the time. earlier i tried to use a while(true) with thread.sleep(300000) at the end, but it crashed always with a ANR, so i tried to use a timer task but now it crashes right after the line AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); with an NullPointerException

package de.nathan.android.droidschool;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;

import java.io.File;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by nathan on 29.08.13.
 */
public class MuteService extends Service
{
    Timer myTimer = new Timer();
    MyTimerTask myTimerTask= new MyTimerTask();
    AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

    public void onCreate()
    {
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int i1, int i2)
    {
        super.onStartCommand(intent, i1, i2);

        myTimer.scheduleAtFixedRate(myTimerTask, 0, 600000); //(timertask,delay,period)

        return START_STICKY;
    }

    public MuteService()
    {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {

                    GregorianCalendar cal = new GregorianCalendar();

                    String tag = null;

                    switch (cal.get(GregorianCalendar.DAY_OF_WEEK))
                        {
                            case GregorianCalendar.MONDAY:
                                tag = "Montag";
                                break;

                            case GregorianCalendar.TUESDAY:
                                tag = "Dienstag";
                                break;

                            case GregorianCalendar.WEDNESDAY:
                                tag = "Mittwoch";
                                break;

                            case GregorianCalendar.THURSDAY:
                                tag = "Donnerstag";
                                break;

                            case GregorianCalendar.FRIDAY:
                                tag = "Freitag";
                                break;
                        }

                        int i = 0;

                        while (i <= 10)
                        {
                            File f = new File("/sdcard/" + i + tag + "fach.txt");
                            if(!f.exists()) break;
                            i++;
                        }

                        i--;

                        int endHr = 0;
                        int endMin = 0;

                        switch (i)
                        {
                            case 0:
                                endHr = 8;
                                endMin = 30;
                                break;

                            case 1:
                                endHr = 9;
                                endMin = 20;
                                break;

                            case 2:
                                endHr = 10;
                                endMin = 20;
                                break;

                            case 3:
                                endHr = 11;
                                endMin = 10;
                                break;

                            case 4:
                                endHr = 12;
                                endMin = 5;
                                break;

                            case 5:
                                endHr = 12;
                                endMin = 55;
                                break;

                            case 6:
                                endHr = 13;
                                endMin = 55;
                                break;

                            case 7:
                                endHr = 14;
                                endMin = 45;
                                break;

                            case 8:
                                endHr = 15;
                                endMin = 35;
                                break;

                            case 9:
                                endHr = 16;
                                endMin = 25;
                                break;

                            case 10:
                                endHr = 17;
                                endMin = 15;
                                break;
                        }

                        if (cal.get(GregorianCalendar.HOUR_OF_DAY) < endHr)
                        {

                            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                        } else if (cal.get(GregorianCalendar.HOUR_OF_DAY) == endHr && cal.get(GregorianCalendar.MINUTE) <= endMin + 5)
                        {

                            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                        } else
                        {

                            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);

                            if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE || audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)
                            {
                                audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                                audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
                            }
                        }

        }
    }
}

LogCat:

08-30 12:44:04.508  23294-23294/de.nathan.android.droidschool D/AndroidRuntime: Shutting down VM
08-30 12:44:04.508  23294-23294/de.nathan.android.droidschool W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41ce6700)
08-30 12:44:04.538  23294-23294/de.nathan.android.droidschool E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to instantiate service de.nathan.android.droidschool.MuteService: java.lang.NullPointerException
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:2561)
        at android.app.ActivityThread.access$1600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1338)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getSystemService(ContextWrapper.java:519)
        at de.nathan.android.droidschool.MuteService.<init>(MuteService.java:21)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1130)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:2558)
        ... 10 more
08-30 12:44:04.548     440-1477/? W/ActivityManager: Force finishing activity de.nathan.android.droidschool/.MainActivity
08-30 12:44:04.848     440-1477/? I/WindowManager: Screenshot max retries 4 of Token{42d5f4e8 ActivityRecord{42624258 u0 de.nathan.android.droidschool/.MainActivity}} appWin=Window{42cc6e50 u0 Starting de.nathan.android.droidschool} drawState=4
08-30 12:44:05.358      440-458/? W/ActivityManager: Activity pause timeout for ActivityRecord{42624258 u0 de.nathan.android.droidschool/.MainActivity}
08-30 12:44:07.068      440-458/? W/ActivityManager: Timeout executing service: ServiceRecord{4330adf8 u0 de.nathan.android.droidschool/.MuteService}
08-30 12:44:07.068      440-458/? I/ActivityManager: Crashing app skipping ANR: ProcessRecord{42cf6020 23294:de.nathan.android.droidschool/u0a10018} Executing service de.nathan.android.droidschool/.MuteService
08-30 12:44:15.518      440-458/? W/ActivityManager: Activity destroy timeout for ActivityRecord{42624258 u0 de.nathan.android.droidschool/.MainActivity}

回答1:

Timer myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();
AudioManager audioManager;

public void onCreate()
{
    super.onCreate();
    audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
}

you need to initialize audioManager inside onCreate.



回答2:

Insted of this:

AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

Do this:

AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);