先说Thread和Service,不少一开始学习Android的人也包括我都存在或多或少的疑惑关于Thread和Service。Thread一般用于开启一个子线程来执行耗时的操作,从而不阻塞主线程,而Service也是用于执行后台操作,一些耗时的任务也是在这里运行。基于后台操作,耗时操作这两个关键字,感觉它俩没有什么区别,充当同样的角色,产生了混淆。但是,事实上它俩一毛钱的关系都没有!!
首先就不在一个级别上,Service是Android四大组件之一 ,与Activity同一个级别。而Thread只是产生一个子线程的工具类,它可以在Activity中创建,也可以在Service中创建。
其次就是,new一个Thread产生一个子线程,在里面执行耗时操作,不堵塞主线程,但是我想告诉你Service是运行在主线程中,你还觉得它俩是一个东西吗。。。你可以在Activity和与它绑定的Service里分别打印出它们当前线程的ID的Log信息通过
Thread.currentThread().getId();
结果我也预料到了,它们是同一个ID值,Service也是运行在主线程中的,因此我们也不能再在Service里面执行耗时操作,如果想要执行耗时操作,也只能在Service里面创建子线程。(推荐IntentService)
然后就是大家把后台和子线程混淆了,后台的意思是不与前台UI,界面更新联系在一起,它默默的服务着前台,即使前台的Activity销毁掉了,只要当前进程不销毁,Service就可以运行保持服务。这也是基于MVC模式,尽量让可视化界面与后台逻辑尽量分开,显得不杂乱。那么问题来了,既然Service也是运行在主线程,Activity也是运行在主线程,我们为什么要在Service里面去创建子线程,在Activity里面创建不也一样吗?其实还是有区别的,在Activity里面创建子线程,当Activity销毁掉了,我们也就失去了这个子线程的引用,无法再对这个线程进行控制管理。一般情况下Activity里面的子线程都是为当前Activity本身服务的,更新一些控件,当Activity销毁了,这个线程的存在也就失去了意义,而Service不一样,任何Activity都可以与之连接,操作其中的方法,管理线程。只要有Context的地方就可以调用startService、stopService、bindService、unbindService来控制。甚至通过接收其他地方的广播来控制,这是Thread做不到的。更不要提跨进程操作。。。Thread更不行。
//Tips:Service后台服务经常因为内存不足而被系统杀死,比如说加载一个较大的网页。在onCreate里面用startForeground(1, notification); 可以提升优先级,notification是一个消息通知,,让y用户可以知道这个线程的运行状态。在onDestroy方法里用stopForeground(notification)停止优先。
AsyncTask :简介及基本使用方法我就不多说了,大家想了解的,这个博客写的很好,可以看一下->AsyncTask
package com.hilton.effectiveandroid.concurrent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.hilton.effectiveandroid.R;
/*
* AsyncTask cannot be reused, i.e. if you have executed one AsyncTask, you must discard it, you cannot execute it again.
* If you try to execute an executed AsyncTask, you will get "java.lang.IllegalStateException: Cannot execute task: the task is already running"
* In this demo, if you click "get the image" button twice at any time, you will receive "IllegalStateException".
* About cancellation:
* You can call AsyncTask#cancel() at any time during AsyncTask executing, but the result is onPostExecute() is not called after
* doInBackground() finishes, which means doInBackground() is not stopped. AsyncTask#isCancelled() returns true after cancel() getting
* called, so if you want to really cancel the task, i.e. stop doInBackground(), you must check the return value of isCancelled() in
* doInBackground, when there are loops in doInBackground in particular.
* This is the same to Java threading, in which is no effective way to stop a running thread, only way to do is set a flag to thread, and check
* the flag every time in Thread#run(), if flag is set, run() aborts.
*/
public class AsyncTaskDemoActivity extends Activity {
private static final String ImageUrl = "http://i1.cqnews.net/sports/attachement/jpg/site82/2011-10-01/2960950278670008721.jpg";
private ProgressBar mProgressBar;
private ImageView mImageView;
private Button mGetImage;
private Button mAbort;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.async_task_demo_activity);
mProgressBar = (ProgressBar) findViewById(R.id.async_task_progress);
mImageView = (ImageView) findViewById(R.id.async_task_displayer);
final ImageLoader loader = new ImageLoader();
mGetImage = (Button) findViewById(R.id.async_task_get_image);
mGetImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loader.execute(ImageUrl);
}
});
mAbort = (Button) findViewById(R.id.asyc_task_abort);
mAbort.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loader.cancel(true);
}
});
mAbort.setEnabled(false);
}
private class ImageLoader extends AsyncTask<String, Integer, Bitmap> {
private static final String TAG = "ImageLoader";
@Override
protected void onPreExecute() {
// Initialize progress and image
mGetImage.setEnabled(false);
mAbort.setEnabled(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(0);
mImageView.setImageResource(R.drawable.icon);
}
@Override
protected Bitmap doInBackground(String... url) {
/*
* Fucking ridiculous thing happened here, to use any Internet connections, either via HttpURLConnection
* or HttpClient, you must declare INTERNET permission in AndroidManifest.xml. Otherwise you will get
* "UnknownHostException" when connecting or other tcp/ip/http exceptions rather than "SecurityException"
* which tells you need to declare INTERNET permission.
*/
try {
URL u;
HttpURLConnection conn = null;
InputStream in = null;
OutputStream out = null;
final String filename = "local_temp_image";
try {
u = new URL(url[0]);
conn = (HttpURLConnection) u.openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setConnectTimeout(20 * 1000);
in = conn.getInputStream();
out = openFileOutput(filename, Context.MODE_PRIVATE);
byte[] buf = new byte[8196];
int seg = 0;
final long total = conn.getContentLength();
long current = 0;
/*
* Without checking isCancelled(), the loop continues until reading whole image done, i.e. the progress
* continues go up to 100. But onPostExecute() will not be called.
* By checking isCancelled(), we can stop immediately, i.e. progress stops immediately when cancel() is called.
*/
while (!isCancelled() && (seg = in.read(buf)) != -1) {
out.write(buf, 0, seg);
current += seg;
int progress = (int) ((float) current / (float) total * 100f);
publishProgress(progress);
SystemClock.sleep(1000);
}
} finally {
if (conn != null) {
conn.disconnect();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
return BitmapFactory.decodeFile(getFileStreamPath(filename).getAbsolutePath());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
mProgressBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Bitmap image) {
if (image != null) {
mImageView.setImageBitmap(image);
}
mProgressBar.setProgress(100);
mProgressBar.setVisibility(View.GONE);
mAbort.setEnabled(false);
}
}
}
基本用法及简介,该博客讲的很好,接下来大家请看AsyncTask源码:
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final InternalHandler sHandler = new InternalHandler();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
<span style="color:#ff0000;"> private final AtomicBoolean mCancelled = new AtomicBoolean();</span>
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link AsyncTask#onPostExecute} has finished.
*/
FINISHED,
}
/** @hide Used to force static handler to be created. */
public static void init() {
sHandler.getLooper();
}
/** @hide */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
protected void onPreExecute() {
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress} is invoked.
* The specified values are the values passed to {@link #publishProgress}.
*
* @param values The values indicating progress.
*
* @see #publishProgress
* @see #doInBackground
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onProgressUpdate(Progress... values) {
}
/**
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* <p>The default implementation simply invokes {@link #onCancelled()} and
* ignores the result. If you write your own implementation, do not call
* <code>super.onCancelled(result)</code>.</p>
*
* @param result The result, if any, computed in
* {@link #doInBackground(Object[])}, can be null
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
@SuppressWarnings({"UnusedParameters"})
protected void onCancelled(Result result) {
onCancelled();
}
/**
* <p>Applications should preferably override {@link #onCancelled(Object)}.
* This method is invoked by the default implementation of
* {@link #onCancelled(Object)}.</p>
*
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* @see #onCancelled(Object)
* @see #cancel(boolean)
* @see #isCancelled()
*/
protected void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally. If you are calling {@link #cancel(boolean)} on the task,
* the value returned by this method should be checked periodically from
* {@link #doInBackground(Object[])} to end the task as soon as possible.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
<span style="background-color: rgb(255, 0, 0);">public final boolean isCancelled() {
return mCancelled.get();
}</span>
/**
* <p>Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.</p>
*
* <p>Calling this method will result in {@link #onCancelled(Object)} being
* invoked on the UI thread after {@link #doInBackground(Object[])}
* returns. Calling this method guarantees that {@link #onPostExecute(Object)}
* is never invoked. After invoking this method, you should check the
* value returned by {@link #isCancelled()} periodically from
* {@link #doInBackground(Object[])} to finish the task as early as
* possible.</p>
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled(Object)
*/
<span style="background-color: rgb(255, 0, 0);"> public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}</span>
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>Note: this function schedules the task on a queue for a single background
* thread or pool of threads depending on the platform version. When first
* introduced, AsyncTasks were executed serially on a single background thread.
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
* executed on a single thread to avoid common application errors caused
* by parallel execution. If you truly want parallel execution, you can use
* the {@link #executeOnExecutor} version of this method
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
* on its use.
*
* <p>This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
* @see #execute(Runnable)
*/
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
* allow multiple tasks to run in parallel on a pool of threads managed by
* AsyncTask, however you can also use your own {@link Executor} for custom
* behavior.
*
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
* a thread pool is generally <em>not</em> what one wants, because the order
* of their operation is not defined. For example, if these tasks are used
* to modify any state in common (such as writing a file due to a button click),
* there are no guarantees on the order of the modifications.
* Without careful work it is possible in rare cases for the newer version
* of the data to be over-written by an older one, leading to obscure data
* loss and stability issues. Such changes are best
* executed in serial; to guarantee such work is serialized regardless of
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
*
* <p>This method must be invoked on the UI thread.
*
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
* convenient process-wide thread pool for tasks that are loosely coupled.
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #execute(Object[])
*/
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
/**
* Convenience version of {@link #execute(Object...)} for use with
* a simple Runnable object. See {@link #execute(Object[])} for more
* information on the order of execution.
*
* @see #execute(Object[])
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
*/
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will not be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
<span style="background-color: rgb(255, 0, 0);">private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}</span>
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
<span style="background-color: rgb(255, 0, 0);">result.mTask.finish(result.mData[0]);</span>
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
我们发现,在doInBackground执行完之后如果没有异常之后,一次执行
postResultIfNotInvoked(get());->postResult(result);->发出消息MESSAGE_POST_RESULT,当InternalHandler接收到消息之后result.mTask.finish(result.mData[0]); 而在finish方法中会判断isCancelled,如果已经cancelled掉则执行onCancelled()方法,当isCancelled()为false时,才会自动调用onPostExecute(result);
<span style="background-color: rgb(255, 255, 255);">private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}</span>
<span style="background-color: rgb(255, 255, 255);"></span><pre name="code" class="java" style="line-height: 18px;">protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
这就是为什么如果不在doInBackground中监测isCancelled(),任务还是会执行完,只是不会提交的现象!并且iscancelled()为true,进度也不会提交。
AsyncTask还有需要注意的问题是它在Android3.0由于线程池的原因,如果同时开启多个异步任务,默认会顺序执行,也就是说它可能会等待其他任务执行完了再去执行另一个任务,这就可能产生卡顿和延迟现象,甚至出现Force close,所以最好不要去同时开启多个异步任务,如果需要需要自定义线程池的数量限制Executors.newFixedThreadPool(7) 其中7是可同时进行的线程数,或者直接设置成无限制Executors.newCachedThreadPool(),要么就直接用Thread。详细可见:AsyncTask线程池