当前位置: 首页 > 面试题库 >

服务在onCreate时使用nullpointerexception崩溃

仲孙雅达
2023-03-14
问题内容

我想每5分钟检查一次服务中的实际时间,然后根据时间将手机静音或取消静音。早些时候,我尝试在线程.sleep(300000)的末尾使用while(true),但是它总是与ANR一起崩溃,所以我尝试使用计时器任务,但是现在它在AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);带有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}

问题答案:
Timer myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();
AudioManager audioManager;

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

您需要在onCreate内初始化audioManager。



 类似资料:
  • 所以我创建一个MapBox实例在AndroidJava。 我使用的版本: 这是我的以下代码: Androidanifest.xml activity_main.xml 应用爪哇: 怀疑行

  • Firebase崩溃报告捕获的异常: 异常java.lang.运行时异常:无法启动活动ComponentInfo{com.talmir.mickinet/com.talmir.mickinet.activities.HomeActivity}:android.content.res.资源$NotFound异常:资源ID 0x7f080058android.app.ActivityThread.pe

  • 通常,当我创建一个Android服务时,我会实现方法,但在我的上一个项目中,这不起作用。我尝试实现,这似乎起作用了。 问题是:当我必须实现一个服务时,需要哪种方法?我必须实现哪些方法?、还是两者兼而有之?每一个角色是什么?

  • 严重:初始化连接器[connector[HTTP/1.1-8080]]org.apache.catalina.LifecyCleException失败:尝试为组件[connector[HTTP/1.1-8080]]进行无效的生命周期转换([before_init]),该组件处于状态[INITIALIZED],位于org.apache.catalina.util.LifecyCleBase.inva

  • 我正在尝试制作一个粘性服务,该服务在死亡后不久就会重新启动(例如,因为Android已经杀死了它以释放内存)。(Un)幸运的是,我在Android 5.0.1上,它有一个漂亮的内存泄漏错误,使真正的测试变得容易。 看着我看到: 后来时间上升到3M,使其不可接受。 我试图使用AlarmManager和重新启动意图来解决这个问题: 然而,这没有帮助。我在日志中找不到任何信息,所以可能是AlarmMan

  • 我正在使用JUnit测试一个DAO类,我得到了一个nullpointerexception,我不知道为什么要启动服务类。以下是测试类: 以下是UserDaoImpl 如何在测试类中注入类?我想nullpointerxeception的原因是dao类没有正确地注入到测试类中