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
?