Similarities and differences between using Toast in IntentService and using Toast in Service, intentservicetoast

Source: Internet
Author: User

Similarities and differences between using Toast in IntentService and using Toast in Service, intentservicetoast

1. Representation

Toast can be displayed normally in Service, but Toast cannot be displayed normally in IntentService. toast is not displayed in system 2.3, but does not disappear in system 4.3.

2. Problem Analysis

You can refer to the official Android documentation and find:

Public Constructorspublic Toast (Context context) Since: API Level 1

Construct an empty Toast object. You must callsetView(View)Before you can callshow().

Parameters
Context The context to use. Usually yourApplicationOrActivityObject.
We can see from the above:

Toast is required to run in the UI main thread, So If Toast can work properly, it must be sent to the UI thread.

Service runs in the main thread, SO Toast is normal.

IntentService runs in an independent thread, SO Toast is not normal.

3. Display Toast in IntentService

Use Handler to display the work of Toast and put it in the main thread. There are two implementation methods.

Method 1: implement the post method of Handler, which is relatively simple.

private void showToastByRunnable(final IntentService context, final CharSequence text, final int duration) {    Handler handler = new Handler(Looper.getMainLooper());    handler.post(new Runnable() {        @Override        public void run() {            Toast.makeText(context, text, duration).show();        }    });}


Method 2: implement the msg method of Handler, which is complicated.

Handler msgHandler = new Handler(Looper.getMainLooper()) {    @Override    public void handleMessage(Message msg) {        Toast.makeText(ToastIntentService.this,msg.getData().getString("Text"), Toast.LENGTH_SHORT).show();        super.handleMessage(msg);    }};private void showToastByMsg(final IntentService context, final CharSequence text, final int duration) {    Bundle data = new Bundle();    data.putString("Text", text.toString());    Message msg = new Message();    msg.setData(data);    msgHandler.sendMessage(msg);}

4. Time-consuming operations

If there are time-consuming operations in the Service, you need to enable a Thread.

IntentService is in an independent thread, so you can perform some time-consuming operations.

5. Consider the differences between AsyncTask and Service

If you are working in the background, you can use the Service, and the Notification can be used for result prompts.

If the job is asynchronous and the UI needs to be updated after the job ends, it is best to use Thread or AsyncTask.

6. Application Instance
@ Overrideprotected void onHandleIntent (Intent intent) {// TODO Auto-generated method stub sendList = intent. getStringArrayListExtra ("sendList"); String content = intent. getStringExtra ("content"); for (String number: sendList) {// create a PendingIntent object PendingIntent pi = PendingIntent. getActivity (SendService. this, 0, new Intent (), 0); SmsManager sManager = SmsManager. getDefault (); // send SMS sManager. sendTextMessage (number, null, content, pi, null); count ++; showMsg ("sent to:" + number + "SMS completed ");} // you are prompted to complete showMsg ("complete SMS sending") by sending a group message);} // you can use Handler to display the work of Toast in the main (UI) public void showMsg (final String msg) {// TODO Auto-generated method stub Handler handler = new Handler (logoff. getMainLooper (); handler. post (new Runnable () {@ Override public void run () {Toast. makeText (SendService. this, msg, Toast. LENGTH_SHORT ). show ();}});}



What are the advantages of IntentService in ANDroid?

IntentService is. startService (Intent) starts a Service that can process asynchronous requests. When using this Service, you only need to inherit the IntentService and override the onHandleIntent (Intent) method to receive an Intent object, stop yourself when appropriate (usually when the work is completed ). all requests are processed in one working thread, and they will be executed alternately (but will not block the execution of the main thread). Only one request can be executed at a time.

This is a message-based service. Every time you start this service, it does not process your work immediately, but first creates the corresponding logoff, handler and added the Message object with the client Intent in MessageQueue. When logoff finds a Message, it obtains the Intent object through the onHandleIntent (Intent) msg. obj) to call your processing program. after processing, your services will be stopped. this means that the life cycle of Intent is consistent with that of the task you process. therefore, this type of download task is very good. After the download task is completed, the Service stops and exits.

How is an exception in the use of intentservice?

The IntentService subclass must have a construction without parameters. However, you only have one parameter-free constructor. Naturally, you cannot automatically create a parameter-free constructor.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.