gpt4 book ai didi

java - 无法停止android后台服务

转载 作者:太空宇宙 更新时间:2023-11-04 13:25:44 25 4
gpt4 key购买 nike

我正在运行以下后台服务:

public class TranslationService  extends IntentService implements ClipboardManager.OnPrimaryClipChangedListener {

private Language mFrom;
private Language mTo;
private String mTranslation;
private ClipboardManager mClipboardManager;

public TranslationService() {
super("hello");
}

public TranslationService(String name) {
super(name);
}

@Override
protected void onHandleIntent(Intent intent) {

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mFrom = (Language) intent.getSerializableExtra(MainActivity.FROM_STRING);
mTo = (Language) intent.getSerializableExtra(MainActivity.TO_STRING);
mClipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(this);

return super.onStartCommand(intent, flags, startId);
}

@Override
public void onPrimaryClipChanged() {

ClipData clip = mClipboardManager.getPrimaryClip();
String copiedText = clip.getItemAt(0).getText().toString();
connectToTranslationApi(copiedText);

//TODO solve concurrency problems if app works inconsistently.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), mTranslation, Toast.LENGTH_SHORT).show();
}
});

}

private void connectToTranslationApi(String copiedPhrase) {

String apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
String fromInitials = mFrom.initials;
String toInitials = mTo.initials;
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key="+
apiKey + "&lang=" +
fromInitials + "-" + toInitials +
"&text="+ copiedPhrase;

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(yandexUrl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
//TODO handle failure
}

@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String jsonData = response.body().string();
try {mTranslation = getTextTranslation(jsonData);}
catch (JSONException e) {e.printStackTrace();}
}
}
});
}

private String getTextTranslation(String jsonData) throws JSONException {
JSONObject data = new JSONObject(jsonData);
String translation = data.getString("text");
translation = translation.replace("]", "")
.replace("[", "")
.replace("\"", "");
return translation;
}

}

该服务在后台运行,并翻译我复制到剪贴板的文本(即使我使用其他应用程序。只有当我从 RAM 中删除启动它的应用程序时,该服务才会停止),这一切都很好。

但是,当我返回应用程序的主要 Activity 并按“停止服务”时,它不会停止。这是启动(并应该停止)服务的代码

         if(mIsServiceRunning == false) {
Intent i = new Intent(MainActivity.this, TranslationService.class);
i.putExtra(FROM_STRING, mLanguageFrom);
i.putExtra(TO_STRING, mLanguageTo);
startService(i);
mIsServiceRunning = true;
startButton.setText("Stop Service");
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, TranslationService.class);
stopService(i);
mIsServiceRunning = false;
startButton.setText("Start Service");
}

有什么想法可以阻止它吗?

最佳答案

我不完全确定您如何确定您的服务仍在运行。但我建议不要将其基于 mIsServiceRunning boolean 值。

您可以使用此方法来确保它是否正在运行:

public static boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

此方法将返回一个 boolean 值,告诉您该服务是否在后台运行,例如,您可以像这样使用它:

if (isServiceRunning(TranslationService.class)) {
Toast.makeText(this, "Service is Running", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Service is NOT Running", Toast.LENGTH_SHORT).show();
}

也许我也错过了它,但我在你的代码中没有看到任何错误。

context.stopService(new Intent(context, TranslationService.class));

应该停止你的服务。

希望对您有帮助,如果没有,请在尝试后尝试提供更多信息。

关于java - 无法停止android后台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com