1
我正嘗試創建一個使用計步器的Android應用程序。目前無法在用戶重新啓動/關閉手機時啓動服務。我正在使用5.1,並且已經在模擬器上完成了測試。由於日誌沒有出現在控制檯中,我不確定它是否正常工作。Android廣播接收器未運行RECEIVE_BOOT_COMPLETED上的服務
任何幫助非常感謝!
應用清單類:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="app.apphub.devon.walkingquest">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".WalkingQuestSplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BootReceiver" android:exported="true" android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filtering>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filtering>
</receiver>
<service android:name=".StepCounterSensorRegister" android:enabled="true" android:exported="true"/>
</application>
</manifest>
啓動接收機類: 公共類BootReceiver擴展廣播接收器{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i("BROADCAST", "WALKING_QUEST_BOOT");
Intent _intent = new Intent("app.apphub.devon.walkingquest.StepCounterSensorRegister");
intent.setClass(context, StepCounterSensorRegister.class);
context.startService(_intent);
//context.startService(_intent);
//Toast.makeText(context,"Airplane mode on",Toast.LENGTH_LONG).show();
}
else {
Log.i("FAIL","BROADCAST FAILED");
}
}
StepCounterSensorRegister類:
public class StepCounterSensorRegister extends Service implements SensorEventListener {
SensorManager sensorManager;
Sensor sensor;
long globalSteps;
boolean flag = false;
@Override
public void onCreate(){
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Must run in background thread
Log.i("START","STEP_COUNTER_STARTED");
registerSensor(sensorManager.SENSOR_DELAY_UI);
return START_STICKY;
}
public void onSensorChanged(SensorEvent event) {
if(!flag){
}
if(event.sensor.getType() == Sensor.TYPE_STEP_COUNTER){
Log.i("STEPS DETECTED",""+globalSteps);
globalSteps++;
}
}
public boolean registerSensor(int accuracy) {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
try {
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}catch (Exception e){
Log.i("ERROR", e.getMessage());
}
if(sensor == null) {
Log.i("FAILED","Sensor returned null");
return false;
}
else {
Log.i("SUCCESS", "Successfully registered sensor");
sensorManager.registerListener(this, sensor, accuracy);
return true;
}
}
非常感謝!刪除額外的權限,並修復intent-filter爲我工作。 –