Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHay Abadi
2,625 PointsProblem with the 3/3 q in Creating a Service part
hey guys, i stock in the part when i need to stop the service with a stopSelf() method, i dont know how to write it . The compiler said it should be after the " twitterClient.update();" in the handelMessage Method.
MainActivity:
public class MainActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.update_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
// TwitterService twitterService = new TwitterService();
Intent intent = new Intent(MainActivity.this, TwitterService.class);
startService(intent);
}
});
}
}
TwitterService:
public class TwitterService extends Service {
TwitterClient twitterClient = new TwitterClient();
TwitterHandler twitterHandler = new TwitterHandler();
@Override
public void onCreate(){
TwitterThread twitterThread = new TwitterThread();
twitterThread.start();
}
class TwitterThread extends Thread {
@Override
public void run() {
Looper.prepare();
// twitterHandler = new TwitterHandler();
Looper.loop();
}
}
class TwitterHandler extends Handler {
@Override
public void handleMessage(Message msg) {
twitterClient.update();
}
}
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
Message message = Message.obtain();
twitterHandler.sendMessage(message);
message.arg1 = startId;
return Service.START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
1 Answer
Josh Gold
12,207 PointsI just kept going on this training course with intention to come back to this problem later. Well today I decided to come back to this problem and try again. Yet again I find that working on something else, taking a break, going out for exercise, and returning another day, allows the solution to come much easier, rather than trying to force out a solution right away.
I found the solution for me is adding the following code immediately after twitterClient.update();
stopSelf();
Josh Gold
12,207 PointsJosh Gold
12,207 PointsI have the same problem. I added the following code immediately after twitterClient.update();
service.stopSelf();
But now it says "Oops! It looks like task 2 is no longer passing."