gpt4 book ai didi

android - 如何停止 IntentService

转载 作者:行者123 更新时间:2023-11-30 00:51:27 32 4
gpt4 key购买 nike

我搜索了很多,但我不知道如何在单击按钮时停止 IntentService。我有一个启动 IntentService 的按钮,然后 progressDialog 显示通过 ResultReceiver 我取回数据。这个应用程序搜索并显示来自设备的照片,所以我认为 IntentService 是正确的方法。但我想在取消按钮上停止它。有这方面的一些例子或良好做法吗?

MainAcitivity:

@Override
public final void onReceiveResult(final int resultCode, final Bundle resultData) {
switch (resultCode) {
case ScanService.STATUS_RUNNING:
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//something to stop
}
});
progressDialog.show();

break;
case ScanService.STATUS_FINISHED:
progressDialog.dismiss();
listOfPictures = resultData.getParcelableArrayList(DATA_KEY);
break;

case ScanService.STATUS_ERROR:
final String error = resultData.getString(Intent.EXTRA_TEXT);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
break;
}
}

扫描服务:

 @Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
super.onDestroy();
}

@Override
protected void onHandleIntent(final Intent intent) {
final ResultReceiver scanResultReceiver = intent.getParcelableExtra(RECEIVER_KEY);
final Bundle bundle = new Bundle();
scanResultReceiver.send(STATUS_RUNNING, bundle);

// some work here

bundle.putParcelableArrayList(DATA_KEY, new ArrayList<>(listOfPictures));
scanResultReceiver.send(STATUS_FINISHED, bundle);
}

最佳答案

从服务外部:(例如按钮点击)

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

从服务内部:

stopSelf();

调试工具:
为了检查您的服务/IntentService 是否存在,请使用此 ADB 命令(从命令行):

adb shell service list |grep <my.app.packagename>

关于android - 如何停止 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40957219/

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