我正在制作一个应用程序,我想在启动时启动并在后台运行。我决定按照本教程将其作为一项服务:
Android - Start service on boot
但是,我希望用户能够打开应用程序并按下按钮来启用/禁用其功能。我有一个名为enabled的布尔值,我用SharedPreferences onStop和onStart保存它:
//Save preferences on stop
@Override
public void onStop() {
super.onStop();
SharedPreferences pref = getSharedPreferences("info", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("AppEnabled", enabled);
editor.commit();
}
//Load preferences on start
@Override
public void onStart() {
super.onStart();
SharedPreferences pref = getSharedPreferences("info", MODE_PRIVATE);
enabled = pref.getBoolean("AppEnabled", true);
//Make button reflect saved preference
Button button = (Button)findViewById(R.id.enableButton);
if(enabled) {
button.setText("Disable");
}
else {
button.setText("Enable");
}
}
如果我打开应用程序并点击按钮,功能就会根据需要进行切换。但是,如果我单击按钮禁用该功能,并关闭应用程序,运行后台的服务仍然认为它已启用。我如何正确地更新服务,使其获得更新后的变量?
编辑:
这是在清单中注册的,并在引导时调用:
/*This class starts MainService on boot*/
package com.example.sayonara;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
public class StartAppServiceOnBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Intent intent = new Intent(context, MainService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
上面的类调用它来启动服务:
/*Called by StartAppServiceOnBoot, starts mainActivity as a service*/
package com.example.sayonara;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MainService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(), MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
发布于 2019-03-20 08:47:59
事实证明,由于我在扩展BroadCastReceiver,这个类是在后台运行的,并且独立于我的应用程序,这就是为什么即使服务关闭,它也会阻止调用。我遵循这个tutorial,以便在服务关闭时禁用我的接收器,它现在可以工作。
https://stackoverflow.com/questions/55232991
复制相似问题