Ошибка при попытке создать backgroundservice в android (сбой приложения)
Я попытался создать приложение с сервисом в фоновом режиме, который прослушивает изменения ускорения. Когда я сейчас пытаюсь запустить службу приложение выходит из строя:
Это сообщение об ошибке:
05-30 19:11:03.764 12650-12650/com.name.flyrecorder E/AndroidRuntime: FATAL EXCEPTION: main Process: com.nameflyrecorder, PID: 12650 java.lang.RuntimeException: Unable to start service com.name.flyrecorder.CheckStart@3d998d with Intent { cmp=com.name.flyrecorder/.CheckStart }: java.lang.IllegalStateException: System services not available to Activities before onCreate() at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4079) at android.app.ActivityThread.access$2400(ActivityThread.java:221) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7225) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate() at android.app.Activity.getSystemService(Activity.java:5762) at com.name.flyrecorder.SensorListener.<init>(SensorListener.java:16) at com.name.flyrecorder.CheckStart$TestAcc.<init>(CheckStart.java:38) at com.name.flyrecorder.CheckStart.onStartCommand(CheckStart.java:29) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4062) at android.app.ActivityThread.access$2400(ActivityThread.java:221) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7225) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Что я уже пробовал:
Мой Главный Праздник:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.name.flyrecorder"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".CheckStart" /> </application> </manifest>
Это моя основная деятельность:
package com.name.flyrecorder; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, CheckStart.class)); } public void startBackgroundListener(View view){ startService(new Intent(this, CheckStart.class)); } }
моя служба:
package com.name.flyrecorder; import android.app.Service; import android.content.Intent; import android.hardware.SensorManager; import android.os.AsyncTask; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class CheckStart extends Service { public CheckStart(){ } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId){ Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show(); new TestAcc().execute(); return Service.START_NOT_STICKY; } @Override public void onDestroy(){ Toast.makeText(this,"Service Stopped", Toast.LENGTH_SHORT).show(); } public class TestAcc extends AsyncTask<Void, Void, Void>{ SensorListener sensorListener = new SensorListener(); double[] sensor_values = new double[2]; @Override protected Void doInBackground(Void... voids) { new Timer().schedule(new TimerTask() { @Override public void run() { sensor_values = sensorListener.getValues(); Log.i("X",String.valueOf(sensor_values[0])); Log.i("Y",String.valueOf(sensor_values[1])); Log.i("Z",String.valueOf(sensor_values[2])); } },2000 ); return null; } } }
И моей помощью sensorlistener:
package com.name.flyrecorder; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v4.app.FragmentActivity; public class SensorListener extends FragmentActivity implements SensorEventListener { Sensor accelerometer; SensorManager sensorManager; double ax,ay,az = 0; public SensorListener(){ sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){ ax = event.values[0]; ay = event.values[1]; az = event.values[2]; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public double[] getValues(){ double[] values = {ax,ay,az}; return values; } }