gpt4 book ai didi

android - 如何在我的程序中间停止 Intent Service?

转载 作者:行者123 更新时间:2023-11-29 16:58:11 26 4
gpt4 key购买 nike

调用 stopService(Intent) 不起作用,即使我按下了 mStopButton

主 Activity

public class MainActivity extends AppCompatActivity {

MyReceiver myReceiver = new MyReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

registerReceiver(myReceiver, new IntentFilter("Start"));

Button mStartButton = (Button) findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyIntentService.class);
startService(intent);
}
});

Button mStopButton = (Button) findViewById(R.id.stop_button);
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyIntentService.class);
intent.setAction("stop");
stopService(intent);
}
});
}

private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int res = intent.getIntExtra("count", -1);
Toast.makeText(MainActivity.this,"Count is " + res,Toast.LENGTH_SHORT).show();
}
}
}

MyIntentService

public class MyIntentService extends IntentService {

public MyIntentService() {
super("MyIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
for (int i=0; i<=100; i++){
Intent intent1 = new Intent();
intent1.setAction("Start");
intent1.putExtra("count",i);
sendBroadcast(intent1);
Log.v("abc",""+i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

如何停止 IntentService

最佳答案

你不能那样停止你的IntentServiceIntentService 自动停止。

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

您可以在 IntentService 中定义一个 boolean isStop 值,并在单击 stop service 按钮时更改该值。您必须检查 for 循环中的 bool 值,例如:

 // when click button
YourIntentService.isStop = true;
// in for loop
for (int i=0; i<=100; i++){
if(isStop) break;
Intent intent1 = new Intent();
intent1.setAction("Start");
intent1.putExtra("count",i);
sendBroadcast(intent1);
Log.v("abc",""+i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

为了最佳实践,您应该使用 LocalBroadCastReceiver 而不是静态 bool 值。

关于android - 如何在我的程序中间停止 Intent Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919278/

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