我为应用程序编写了一个代码,当手机以某个角度倾斜时会发出蜂鸣声。它在开始时工作正常,但是当我向第7或第8次倾斜电话时,它不再发出哔哔声。当我检查应用程序状态时,它显示为正在运行。我的服务代码是
public class TheService extends Service implements SensorEventListener {
public static final String TAG = TheService.class.getName();
public static final int SCREEN_OFF_RECEIVER_DELAY = 500;
private SensorManager mSensorManager = null;
private WakeLock mWakeLock = null;
private float lastY;
MediaPlayer mp1;
private MediaPlayer mMediaPlayer;
/*
* Register this as a sensor event listener.
*/
private void registerListener() {
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
/*
* Un-register this as a sensor event listener.
*/
private void unregisterListener() {
mSensorManager.unregisterListener(this);
}
public BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive("+intent+")");
if (!intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
return;
}
Runnable runnable = new Runnable() {
public void run() {
Log.i(TAG, "Runnable executing.");
unregisterListener();
registerListener();
}
};
new Handler().postDelayed(runnable, SCREEN_OFF_RECEIVER_DELAY);
}
};
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged().");
}
public void onSensorChanged(SensorEvent event) {
Log.i(TAG, "onSensorChanged().");
lastY = event.values[2];
if (lastY <9 && lastY > 8) {
mMediaPlayer = MediaPlayer.create(this, R.raw.help);
mMediaPlayer.start();
}
}
@Override
public void onCreate() {
super.onCreate();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
PowerManager manager =
(PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
@Override
public void onDestroy() {
mMediaPlayer.release();
unregisterReceiver(mReceiver);
unregisterListener();
mWakeLock.release();
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(Process.myPid(), new Notification());
registerListener();
mWakeLock.acquire();
return START_STICKY;
}
}
我的主要活动代码是
public class MainActivity extends Activity {
public static final String TAG = HelpIMFalling.class.getName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onResume() {
super.onResume();
startService(new Intent(this, TheService.class));
}
}
我不确定android是否正在杀死它或我的代码中有任何问题。如果Android正在这样做,该应用程序将不会显示为在后台运行。请帮助。
答案 0 :(得分:0)
你有任何日志吗?
避免重新创建MediaPlayer:
if(mMediaPlayer == null)
mMediaPlayer = MediaPlayer.create(this, R.raw.help);