2013-09-28 161 views
0

我有一個睡眠機器應用程序,如果手機進入待機狀態,我想要繼續播放聲音。我剛剛編輯了添加了喚醒鎖,並將其添加到清單中。它沒有正常工作,但我不知道爲什麼。使用喚醒鎖

package com.androidsleepmachine.gamble; 

import android.app.Activity; 
import android.content.Context; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.PowerManager; 
import android.view.KeyEvent; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Spinner; 

public class Ship extends Activity implements View.OnClickListener { 
public static final Integer[] TIME_IN_MINUTES = { 30, 45, 60, 180, 360 }; 
public MediaPlayer mediaPlayer; 
public Handler handler = new Handler(); 
public Button button2; 
public Spinner spinner2; 
private PowerManager.WakeLock wl; 
// Initialize the activity 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.ship); 
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNjfdhotDimScreen"); 


    button2 = (Button) findViewById(R.id.btn2); 
    button2.setOnClickListener(this); 
    spinner2 = (Spinner) findViewById(R.id.spinner2); 
    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, 
android.R.layout.simple_spinner_item, TIME_IN_MINUTES); 

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   
    spinner2.setAdapter(adapter); 
} 

// Play the sound and start the timer 
private void playSound(int resourceId) { 
    // Cleanup any previous sound files 
    cleanup(); 
    // Create a new media player instance and start it 
    mediaPlayer = MediaPlayer.create(this, resourceId); 
    mediaPlayer.start(); 
    // Create the timer to stop the sound after x number of milliseconds 
    int selectedTime = TIME_IN_MINUTES[spinner2.getSelectedItemPosition()]; 
    handler.postDelayed(runnable, selectedTime * 60 * 1000); 
} 

// Handle button callback 
@Override 
public void onClick(View v) { 
    switch (v.getId()) { 
     case R.id.btn2: 
      playSound(R.raw.ocean_ship); 
      break; 
    } 
} 
protected void onStop() 
    { 

     cleanup(); 
     super.onStop(); 
    } 
// Stop the sound and cleanup the media player 
public void cleanup() { 
    if (mediaPlayer != null) { 
     mediaPlayer.stop(); 
     mediaPlayer.release(); 
     mediaPlayer = null; 
     wl.release(); 
    } 
    // Cancel any previously running tasks 
    handler.removeCallbacks(runnable); 
} 

// Runnable task used by the handler to stop the sound 
public Runnable runnable = new Runnable() { 
    public void run() { 
     cleanup(); 
    } 
}; 
} 
+0

這個問題在任何方面如何與eclipse有關? – Leo

+0

我在eclipse中編程 – user2727048

回答

0

您可以通過喚醒鎖來使其發生。它的部分Powermanager api

可以找到詳細的解釋here.

+0

我添加了代碼,但是當我點擊電源按鈕以切斷屏幕時,喚醒鎖定仍然不起作用。 – user2727048