我的服务类没有调用,没有错误,崩溃报告或异常!调用服务之前和之后的行正在运行,我也使用isMyServiceRunning方法进行了检查,但是它没有工作..
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, MyService.class);
startService(i);
Toast.makeText(this,"to check if this is working",Toast.LENGTH_LONG).show();
}
}
服务类:
public class MyService extends Service implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
double ax, ay, az;
@Override
public void onCreate() {
super.onCreate();
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (mSensor != null) {
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
} else {
stopSelf();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
ax = event.values[0];
bx = event.values[1];
cx = event.values[2];
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
}
清单文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.star.sproject">
<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"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="false"
android:exported="false"></service>
</application>
请帮忙!
答案 0 :(得分:0)
尝试在manifest.xml中将服务声明的属性android:enabled
设置为true
,否则无法实例化服务。
https://developer.android.com/guide/topics/manifest/service-element.html
答案 1 :(得分:0)
这样做
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>