android


How to stop Intent Service in middle of my program?


Calling stopService(Intent) does not work, even though I am pressing mStopButton.
MainActivity
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();
}
}
}
}
}
How can I stop the IntentService?
You cant stop your IntentService that way. IntentService is stopped itself automatically.
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.
You can define a boolean isStop value in your IntentService and change the value when stop service button is clicked. You have to check the boolean in the for loop like:
// 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();
}
}
For best pratice, you should use LocalBroadCastReceiver instead of static boolean value.
Intent service stops by itself when work is done you don't need to explicitly stop it.

Related Links

How to align six imagebuttons in 2 columns with 3 rows in android studio?
Google Map Implementation in Viewpager, Error Unable to get provider com.google.firebase.provider.FirebaseInitProvider
set Hindi as TextToSpeech language in android programatically
How to make a link redirecting on Apple store or Google play
How to rotate image slowly in android?
Find element by class-name and content-desc in web context selenium
Retrofit - Failure in SSL library, usually a protocol error
Redirect site page on Intel XDK
How to implement own cast.receiver.media.Player
Titanium View.toImage() and base64 encode not always decoding properly
How does Firebase crash reporting initialize
AVD errors with HAX on Android Studio 2.1
Slider and ngModel lagging with finger slide
How to set proper version control for Ionic project
Android Studio Gradle task stuck
Android file access questions

Categories

HOME
asp.net-web-api
api
design-patterns
apache-flink
forms
depth
case
apiblueprint
vscode-extensions
ms-access-2016
edge
web-hosting
telegram-bot
interpolation
crystal-reports-2013
missing-data
modal-dialog
pega
php-5.6
package.json
dimensional-modeling
dreamweaver
mapstruct
shortest-path
sse
swagger-2.0
ag
poedit
aggregation
highstock
interpreter
strongname
jquery-multiselect
uitapgesturerecognizer
mobx
postback
fstream
carriage-return
pop3
sim-toolkit
salesforce-communities
graphhopper
projects-and-solutions
setup.py
tasm
android-ibeacon
bindingnavigator
outputcache
clang++
dynamic-linq
openal
linter
tf
amq
context-sensitive-grammar
boo
pdf-conversion
d3-force-directed
cpu-cache
rocks
docpad
pure-css
simplepie
autosar
centrifuge
dup
vorpal.js
respondcms
clipboard.js
qiime
deep
phpwebsocket
thread-sleep
jaunt-api
atan2
character-replacement
r-package
intel-c++
fuelcms
toolkit
iced-coffeescript
mraid
primitive-types
spy++
mobility
radiant
fpdi
multitasking
windows-embedded-standard
rfc5322
gwt-openlayers
neos-server
nebula
android-icons
traceability
resource-management
web-notifications
patricia-trie
kqueue
google-ajax-api
clrstoredprocedure
w3c-geolocation
qglwidget
squishit
dot-emacs
blender-2.49
asynchronous-wcf-call
java1.4
information-management
pnrp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App