2016-11-08 71 views
-1

我試圖將我的應用程序的一部分轉換爲服務,因爲它需要在後臺運行。現在,按鈕應啓動點擊時停止該服務,:服務未啓動 - 空對象參考

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_aim_start); 
    tThis = this; 
    calc.init(); 
    status = (TextView) findViewById(R.id.statusView); 
    output = (TextView) findViewById(R.id.lbl_output); 
    final Intent intent = new Intent(this, AIMService.class); 
    startButton = (Button) findViewById(R.id.start_aim); 
    startButton.setOnClickListener(new View.OnClickListener(){ 
     public void onClick(View v) { 
      if (!func) { 
       func = true; 
       startButton.setText("Stop AIM"); 
       status.setText("AIM-Started"); 
       tThis.startService(intent); //I read somewhere that it would need a 
              //context, but it didn't work 
      } else { 
       func = false; 
       startButton.setText("Start AIM"); 
       tThis.stopService(intent); 
      } 
     } 
    }); 

但是現在,我收到以下錯誤:

FATAL EXCEPTION: main 
     Process: com.protonmail.fabian.schneider.aim, PID: 6081 
     java.lang.RuntimeException: Unable to start service [email protected] with Intent { cmp=com.protonmail.fabian.schneider.aim/.AIMService }: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.app.IntentService$ServiceHandler.obtainMessage()' on a null object reference 
     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3336) 
     at android.app.ActivityThread.access$2200(ActivityThread.java:177) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1530) 
     t android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5912) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.app.IntentService$ServiceHandler.obtainMessage()' on a null object reference 

的服務在清單中聲明。 的清單:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.protonmail.fabian.schneider.aim"> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".AIM_start" 
        android:label="AIM" 
        android:configChanges = "orientation" 
        android:screenOrientation="portrait"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <service android:name=".AIMService" /> 
    </application> 

</manifest> 

的服務:

公共類AIMService擴展IntentService {

private SoundPool soundPool; 
private AudioManager audioManager; 
private static final int max_streams = 1; 
private static final int streamType = AudioManager.STREAM_MUSIC; 
boolean loaded; 
public static String strengthArr[] = new String[4]; 

static { 
    strengthArr[0] = "90,110,90,110"; 
    strengthArr[1] = "50,89,111,150"; 
    strengthArr[2] = "0,49,151,200"; 
    strengthArr[3] = "-50,-1,201,-250"; 
} 

static String downURL = "http://services.swpc.noaa.gov/text/goes-magnetometer-primary.txt"; 
static String errPatt = "-1.00e+05"; 

private float volume; 

private int strengthSound[] = new int[5]; 

@Override 
public void onCreate(){ 

    System.out.println("started audio initialization"); 
    //AUDIO 
    audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); 
    float currentVolumeIndex = (float) audioManager.getStreamVolume(streamType); 
    float maxVolumeIndex = (float) audioManager.getStreamMaxVolume(streamType); 
    this.volume = currentVolumeIndex/maxVolumeIndex; 
    //this.setVolumeControlStream(streamType); 


    if(Build.VERSION.SDK_INT >= 21) { 
     AudioAttributes audioAttrib = new AudioAttributes.Builder() 
       .setUsage(AudioAttributes.USAGE_GAME) 
       .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 
       .build(); 
     SoundPool.Builder builder = new SoundPool.Builder(); 
     builder.setAudioAttributes(audioAttrib).setMaxStreams(max_streams); 
     this.soundPool = builder.build(); 
    } else{ 
     this.soundPool = new SoundPool(max_streams, AudioManager.STREAM_MUSIC, 0); 
    } 
    //Sound pool load complete 
    this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { 
     @Override 
     public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { 
      loaded = true; 
      System.out.println("finished loading resources"); 
      //publishProgress("finished loading resources"); 
      //SoundPool.Builder(new SoundPool.Builder()).play(strengthSound[0],volume,volume,1,0,1f); 
      /*MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.strength0); 
      MediaPlayer mediaPlayer2 = MediaPlayer.create() 
      mediaPlayer.start();*/ 
     } 
    }); 
    System.out.println("starting tone init"); 
    this.strengthSound[0] = this.soundPool.load(this, R.raw.strength0,1); 
    this.strengthSound[1] = this.soundPool.load(this, R.raw.strength1,1); 
    this.strengthSound[2] = this.soundPool.load(this, R.raw.strength2,1); 
    this.strengthSound[3] = this.soundPool.load(this, R.raw.strength3,1); 
    this.strengthSound[4] = this.soundPool.load(this, R.raw.strength4,1); 
    System.out.println("fin tone init"); 
} 


public AIMService(){ 
    super("AIMService"); 
} 
@Override 
protected void onHandleIntent (Intent intent) { 
    //WORK 

    while (true) { 

     System.out.println("before publishProgress Update"); 
     //publishProgress("Calculation Started"); 

     AIMService.dataImport dI; 
     try { 
      dI = new AIMService.dataImport(downURL); 
      String calcData; 
      calcData = dI.download(); 

      System.out.println(calcData); 
      AIMService.preAnalysis pA; 
      pA = new AIMService.preAnalysis(calcData); 
      boolean dateOk; 
      dateOk = pA.preanalyse(); 
      if (dateOk) { 
       System.out.println("Data Date is okay"); 
       //call last line downloader 
       dI = new AIMService.dataImport(downURL); 
       String lastLine; 
       lastLine = dI.downloadLast(); 
       if (!lastLine.contains(errPatt)) { 
        //data is ok 
        System.out.println("Current data is okay"); 
        System.out.println("Current data: " + lastLine); 
        System.out.println("Starting analysis"); 

        AIMService.analyse an = new AIMService.analyse(lastLine); 
        int strength; 
        strength = an.analyseData(); 
        if (strength != -1) { 
         System.out.println("Strength: " + strength); 
         //outputText(Integer.toString(strength)); 
         publishProgress(Integer.toString(strength)); 
         //return Integer.toString(strength); 


        } else { 
         System.out.println("Strength not found"); 
         //send signal for out of scope to output 
         publishProgress("-1"); 
         //return "-1"; 
        } 
       } else { 
        System.out.println("Current data is not okay"); 
        publishProgress("Current data is not okay"); 
        //send signal for satellite down to output 
        publishProgress("-1"); 
        //return "-1"; 
       } 

      } else { 
       System.out.println("Data Date not okay"); 
       publishProgress("Data Date not okay"); 
       //send signal for satellite down to output 
       publishProgress("-1"); 
       //return "-1"; 
      } 


      //catch statements 
     } catch (MalformedURLException e) { 
      System.out.println("MalformedUrlException for dI allocation"); 
     } catch (IOException e) { 
      System.out.println("IOException in dI alloc"); 

      //check inet conn/send satellite down to output 
      return; 
     } 
     //return "ERROR"; 
    } 
} 

我做了什麼錯?

+1

您可以發佈清單 –

+0

我加入清單的問題 –

+0

確定崗位服務以及 –

回答

0

只是爲了完成主題;這裏是對答案的總結:

就像Alex Shutov告訴我的,我將Intent Service改爲服務。 我做到了這一點通過下面的官方文檔: Documentation

對於所有感興趣的代碼和/或項目: GitHub AIM

0

您使用IntentService,它創建一個單獨的線程來執行命令中的任務,然後它立即終止。你應該在onHandleIntent(Intent intent)方法中做所有的工作。 在你的情況下使用普通服務,而不是IntentService。

+0

在我的服務中有一個onCreate,它會執行一些小事...而主要工作是在onHandleIntent(Intent intent)中完成的 - 我沒有看到我的錯誤... –

+0

沒有停止IntentService的意思,一旦工作完成,它將自動停止 –

+0

該服務是一種永不終止的計算,可以生成發送到音頻輸出的音調。 所以我認爲停止服務將是一個好主意,如果有人厭倦了噪音= P –