Copyright Statement: No reprinting without the permission of the blogger
AsyncTask
To understand AsyncTask asynchrony, we need to know about asynchronous tasks (multi-threading), what is thread, it can be said that threads are like watching TV while eating. AsyncTask is to facilitate the operation of background threads to update UI, essentially Handler asynchronous message processing mechanism.
Learning AsyncTask requires knowing its parameters < Params, Progress, Result>, the methods it implements, such as onPreExcecute(), onPostExecute(), background thread operation doInBackground(), display progress onProgressUpdate(), etc. I'm familiar with it here. Now I'll talk about how to use it in code.
Here we create a class
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //Here we create an internal class that inherits AsyncTask public class DownloadAsyncTask extends AsyncTask<String,Integer,Boolean>{ } }
Let's click here to see the underlying Async Task
public abstract class AsyncTask<Params, Progress, Result> { //Params is the type parameter, Progress is the progress, and the result is returned. }
Here we inherit and implement it in the following ways
//Before asynchronous tasks @Override protected void onPreExecute() { super.onPreExecute(); // Dead work } @Override protected Boolean doInBackground(String... strings){ //Handling events } @Override protected void onPostExecute(Boolean aBoolean){ super.onPostExecute(aBoolean); //Execution, execution result processing } //When our progress is changing @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); //Receive progress, and then process: also in the UI thread. } //cancel /*@Override protected void onCancelled(Boolean aBoolean) { super.onCancelled(aBoolean); } @Override protected void onCancelled() { super.onCancelled(); }*/
Here, onPreExcecute (before execution), doInBackground (in execution), onPostExecute (after execution), onProgressUpdate are usually executed.
Here is an example of how to download an apk from the network and request network data to download files. Here I'll explain in more detail how to get url and request the network.
Set up a button to click on the download file
//Define a method private void setButtonListener(){ mDownloadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DownloadAsyncTask asyncTask = new DownloadAsyncTask(); asyncTask.execute(APK_URL); } }); }
To explain here, it is understandable that applying for asyncTask application is to create objects. Public class Download AsyncTask extends AsyncTask < String, Integer, Boolean > {...}, then this'execute'has not been mentioned yet, so click to see the source code.~
@MainThread public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } //Implementation by execute
Here's the code in execution
//Explain that Boolean here is defined by this public class DownloadAsyncTask extends AsyncTask<String,Integer,Boolean>{ } //<Params, Progress, Result> //String... strings represent arrays, variable parameters, and may be empty @Override protected Boolean doInBackground(String... strings){ }
Before execution
@Override protected void onpreExecute(){ super.onPreExecute(); //Solving UI problems }
The code in execution is downloaded:
//String... as an array @Override protected Boolean doInBackground(String... strings) { //Prevention is empty. if (strings != null && strings.length>0){ //The parameter passed in is url, which is // DownloadAsyncTask asyncTask = new DownloadAsyncTask(); //asyncTask.execute(APK_URL); //Decision String apkurl = strings[0]; try{ //Give you a download address url, then you need to create a URL object URL url = new URL(apkurl);//String apkurl = strings[0]; //Construct a URLConnection to open the connection url.openConnection() URLConnection urlConnection = url.openConnection(); //Input stream reads data InputStream inputStream = urlConnection.getInputStream(); //Next, get the total length of the downloaded content int contentLength = urlConnction.getContentLength(); //Next is to find a place to store it, just follow where it is in the directory, as a string. String mFilePath=Environment.getExternalStorageDirectory() + File.separator + FILE_NAMEļ¼ // Environment. getExternal Storage Directory () is a directory, which is more practical. // File.separator is equivalent to'/' // FILE_NAME is the file name and can be changed to "what.apk". //Processing the download address File apkFile = new File(mFilePath); //Next, the file is entered into the directory. //Read before write //Judgement file if(apkFile.exists()){ boolean result = apkFile.delete(); if(!result){ return false; } } //Document progress bar, how many downloads have been made int downloadSize = 0; //Define the length of a read array, and proceed to... byte[] bytes = new byte[1024];//1024 is not stipulated, you can decide for yourself //How long to read? int length; //Create an output stream, write OutputStream outputStream = new FileOutputStream(mFilePath);//Write to this path while( (length = inputStream.read(bytes)) != -1){ outputStream.write(bytes,0,length); downloadSize+=length; //Sending progress publishProgress(); } .... } }
After execution
@Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); //Also in the main thread, executing result processing //Processing UI }
Final progress change
//When our progress is changing @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (values != null && values.length >0){ } }
The key point is to add network permissions and read permissions.
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
ListView
ListView is a control we often use in Android development to display data. We can see lists of articles everywhere in Wechat lists.
Deepen understanding
public class AppListAdapter extends BaseAdapter{} public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter {} public interface ListAdapter extends Adapter {} public interface SpinnerAdapter extends Adapter {}
Create layout
<ListView android:id="@+id/main_list_view" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView>
Implementing control declarations
private ListView mListView; mListView=findViewById(R.id.main_list_view);
Step: Learn about Adapter
public class AppListAdapter extends BaseAdapter{ }
//Get package name String packageName = mAppInfos.get(position).activityInfo.packageName; //// Get the application name String className = mAppInfos.get(position).activityInfo.name; //Stitching-Clicking Method ComponentName componentName = new ComponentName(packageName,className);
final Intent intent = new Intent(); //Setting Component Names through Intent intent.setComponent(componentName); startActivity(intent);
The abstract method in BaseAdapter
public int getCount(); public Object getItem(int arg0); public long getItemId(int arg1); public View getView(int position, View convertView, ViewGroup parent);
public View getView(int position, View covertView, ViewGroup parent){ if(converView == null){ converView = mInflater.inflate(R.layout.list_item, null); } }
static class ViewHolder{ public ImageView image; public TextView title; } @Override public View getView(int position,view convertView, ViewGroup parent){ ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.list_item, null); holder. holder. convertView.setTag(holder); }else{ holder=(ViewHolder)convertView.getTag(); } }
Editor: Dashu
Location: Sharing Android & Java Knowledge Points