我寫了一個應用程序的代碼,當手機以某個角度傾斜時,該應用程序會發出嗶聲。它在開始時工作正常,但當我第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已經這樣做了,該應用程序將不會顯示爲在後臺運行。請幫助。
任何logcat的輸出? – ByteHamster 2015-04-03 20:31:10
我不知道如何檢查!你可以指導 – Usman 2015-04-03 20:33:01