【发布时间】:2019-03-19 02:58:17
【问题描述】:
我正在制作一个我想在启动时启动并在后台运行的应用程序。我决定按照本教程将其作为一项服务:
Android - Start service on boot
但是,我希望用户能够打开应用并按下按钮来启用/禁用其功能。我使用 SharedPreferences onStop 和 onStart 保存了一个名为 enabled 的布尔值:
//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");
}
}
【问题讨论】:
-
你们的服务是做什么的?你应该让它在工作过程中检查首选项的值
-
@SteelToe 该服务阻止电话呼叫。它会检查 main 中的局部变量“enable”是真还是假。你是说我需要检查首选项而不是变量吗?上面的代码不会更新变量吗?我认为如果应用程序实例被关闭,它会更新变量,该变量也会在服务中更新它。
-
哦,您想在用户切换到禁用状态时停止服务吗?
-
@SteelToe 不,我希望阻止调用的代码在检查变量后退出。
-
意思是你想杀死正在检查调用的服务?
标签: android android-intent sharedpreferences android-service