Android multithreaded programming method and opening steps

Source: Internet
Author: User

  

Huaqing Vision Lecturer

Two ways to implement threading

Using the inherited method

Class MyThread extends thread{

@Override

public void Run () {

Dealing with specific logic

}

}

To start this thread, create a new instance in the main thread and call its start () method.

Use the way to implement runnable excuses

Class MyThread implements runnable{

@Override

public void Run () {

Dealing with specific logic

}

}

When off-the-shelf, use:

MyThread MyThread = new MyThread ();

New Thread (MyThread). Start ();

Anonymous class method to implement Runnable is the same.

New Thread (New Runnalbe () {

@Override

public void Run () {

Handling Specific logic

}

}). Start ();

Asynchronous operation

Like many GUI libraries, the Android UI is also thread insecure, so we can't update UI elements in a child thread.

We need to pass the UI update operation to the main thread through an asynchronous operation through a child thread communicating to the main thread.

The method of handler and message passing together

Here, there are message, Handler, MessageQueue and looper in effect.

1, message is the transmission between the county.

2. Handler is the processor for sending and processing messages

3, MessageQueue is the meaning of Message Queuing, storing messages sent through handler.

4. Looper is the steward of MessageQueue in each thread.

Handler Handler = new Handler () {

public void Handlemessage (Message msg) {

Switch (msg.what) {

Case Updata_text:

Txvhello.settext ("Nice to meet you!");

Break

Default

Break

}

}

};

8new Thread (New Runnable () {

@Override

public void Run () {

Message msg = new Message ();

Msg.what = Updata_text;

Handler.sendmessage (msg);

}

}). Start ();

Using the async Task

An Async task is an abstract class that we want to use, and we need to deal with it first.

3 Parameters:

1. The params needs to pass in the parameters when executing Asynctask, which can be used in the background service.

2. Progress if you need to display the current progress on the interface, use the generic type here as the progress unit.

3. After the result task is executed, the results are returned.

4 Overriding methods:

1, OnPreExecute ()

2, Doinbackground (... )

3, Onprogressupdate (... )

4. OnPostExecute (Result)

public class Downloadtask extendsasynctask{

TextView txvdownloading;

ProgressBar ProgressBar;

@Override

protected void OnPreExecute () {

Super.onpreexecute ();

Progressbar.setmax (100);

}

Public Downloadtask (TextView txvdownloading, ProgressBar ProgressBar) {

this.txvdownloading = txvdownloading;

This.progressbar = ProgressBar;

}

@Override

Protected Integer doinbackground (Void ... params) {

int count = 0;

for (int i =100; i > 0; i--) {

count++;

Publishprogress (count);

try {

Thread.Sleep (500);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

return count;

}

@Override

protected void Onprogressupdate (Integer ... values) {

int a = values[0];

LOG.D ("TAG", A + "");

Progressbar.setprogress (a);

}

@Override

protected void OnPostExecute (integer integer) {

Super.onpostexecute (integer);

if (integer.equals (100)) {

Txvdownloading.settext ("Done");

}else{

Txvdownloading.settext ("Downloading");

}

}

}

In mainactivity, you only need to write:

1new Downloadtask (Txvshow, Prgsdownload). Execute ();

Can.

Service

What is a service: service is one of the four components of Android that runs in the background

Create a service

Create a class that inherits the service,

Where the Onbind method is overridden by default, there are 3 other important methods, OnCreate (), Onstartcommand (), OnDestroy ().

1, the OnCreate () method is called when the service is created

2, Onstartcommand () will be called every time the service starts

3, OnDestroy () will be called when the service is destroyed.

Each service must be registered in Androidmanifest.xml in order to take effect.

Starting and shutting down services

By intent we can open and close the service

Switch (V.getid ()) {

Case R.id.btn_start:

Intent starttntent = new Intent (this, myservice.class);

StartService (starttntent);

Break

Case R.id.btn_stop:

Intent stopintent = new Intent (this, myservice.class);

StopService (stopintent);

Break

Default

Break

}

Onbind method, binding service

Private Downloadbinder Mbinder = new Downloadbinder ();

Class Downloadbinder extends binder{

public void Startdownload () {

LOG.D ("TAG", "startdownload");

}

public int getprogress () {

LOG.D ("TAG", "getprogress executed");

return 0;

}

}

@Nullable

@Override

Public IBinder Onbind (Intent Intent) {

return mbinder;

}

Private Serviceconnection connection = Newserviceconnection () {

@Override

public void onserviceconnected (componentname name, IBinder service) {

Downloadbinder = (myservice.downloadbinder) service;

Downloadbinder.startdownload ();

Downloadbinder.getprogress ();

}

@Override

public void onservicedisconnected (componentname name) {

}

};

Case R.id.btn_bindstart:

Intent bindintent = new Intent (this, myservice.class);

Bindservice (bindintent,connection,bind_auto_create);

Break

Case R.id.btn_bindstop:

Unbindservice (connection);

The life cycle of the server:

Slightly.

More Services---front desk service

Similar to the use of notifications, build notification objects in the OnCreate code, build intent objects, Pendingintent,setlatesteventinfo, and then Startforeground methods

public void OnCreate () {

Super.oncreate ();

Notification Notification = newnotification (R.drawable.ic_launcher, "Notification Comes", System.currenttimemillis () );

Intent notificationintent = new Intent (this, mainactivity.class);

Pendingintent pendingintent = pendingintent.getactivity (this,0,notificationintent,0);

Startforeground (1,notification);

}

7. Intentservice

To avoid time-consuming logic in the main thread, we need to use Android's multithreaded programming method to put time-consuming logic into the thread.

@Override

public int Onstartcommand (Intent Intent, int flags,int startid) {

New Thread (New Runnable () {

@Override

public void Run () {

Handling time-consuming logic

}

}). Start ();

Return Super.onstartcommand (Intent, flags, Startid);

}

After the time-consuming logic has been executed, if we want the service to shut down automatically after the content has been processed, then adding the Stopself () method at the end of the time-consuming logic is a good choice.

Of course, you can use the Intentservice class here, it can simply create an asynchronous, will automatically stop the service.

public class Myintentservice extends intentservice{

/**

* Creates an intentservice. Invoked by your subclass ' s constructor.

*

*

*/

Public Myintentservice () {

Super ("Myintentservice");

}

@Override

protected void Onhandleintent (Intent Intent) {

for (int a = ten; a > 0; a--) {

try {

Thread.Sleep (500);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

LOG.D ("TAG", "+a");

}

}

@Override

public void OnDestroy () {

Super.ondestroy ();

LOG.D ("TAG", "OnDestroy");

}

}

ASE R.id.btn_intentservice:

Intent Intentservice = newintent (This,myintentservice.class);

StartService (Intentservice);

Break

  

>>> more Excellent technology blog in huaqing Vision Embedded College View

This article is from the "Embedded Learning World" blog, please be sure to keep this source http://farsight.blog.51cto.com/1821374/1757488

Android multithreaded programming method and opening steps

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.