如何更改服务的首选项?

问题描述 投票:0回答:1

我正在创建一个我想在启动时启动并在后台运行的应用程序。我决定按照本教程使其成为一项服务:

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");
    }
}
android android-intent sharedpreferences android-service
1个回答
0
投票

事实证明,因为我正在扩展BroadCastReceiver,所以该类在后台运行并独立于我的应用程序,这就是为什么即使关闭服务也会阻止调用。我关注这个tutorial,以便在服务关闭时禁用我的接收器并且现在可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.