Why isn't my service running? (As judged by displaying Toast message.)
I am trying to make a service in the background so I can run a loop that requests a page every x minutes. This is my service in the manifest:
<se开发者_Python百科rvice android:name=".webToSMS" android:enabled="true" />
And here is my service being started (in the main activity):
Intent intent = new Intent(this, webToSMS.class);
startService(intent);
And finally, this is my service class:
public class webToSMS extends IntentService {
public webToSMS() {
super("webToSMS");
}
@Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I was following the guide at Android and this is what it told me to do. What I am expecting is a toast to pop up saying "Hello toast!" when this service is run. Eventually when this works I will put a loop which will request a page every x minutes.
Your service is running, it's just not displaying the toast because you are not on the UI thread.
If you want to see a toast try this instead
Handler HN = new Handler();
private class DisplayToast implements Runnable {
String TM = "";
public DisplayToast(String toast){
TM = toast;
}
public void run(){
Toast.makeText(getApplicationContext(), TM, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onHandleIntent(Intent intent) {
HN.post(new DisplayToast("New Toast on UI Thread"));
}
精彩评论