Android callback function 2: application instance and android callback function
If you do not understand the android callback concept, see android callback function 1: Basic concepts.
1. Define Interfaces
package com.app.util;public interface ZYJCallBack { public void dataResult( String resultString ) ; public void progress( Integer progress ) ; public void start() ;}
2. Entity
Package com. app. util; import android. OS. asyncTask; public class ZYJAsyncTask extends AsyncTask <String, Integer, String> {ZYJCallBack zyjCallBack; // start @ Override protected void onPreExecute () {super. onPreExecute (); zyjCallBack. start ();}/*** Special Note: publishProgress (10); * This sentence must be written, otherwise onProgressUpdate (), this method will not be called back */@ Override protected String doInBackground (String... params) {publishProgress (10); publishProgress (20); publishProgress (50); publishProgress (100); return "HAHAHA, operation completed ";} // onProgressUpdate method is used to update the progress information @ Override protected void onProgressUpdate (Integer... progresses) {zyjCallBack. progress (progresses [0]);} @ Override protected void onPostExecute (String result) {super. onPostExecute (result); zyjCallBack. dataResult (result);} public void setCallBackListener (ZYJCallBack zyjCallBack) {this. zyjCallBack = zyjCallBack ;}}
3. Callback
Package com. android10; import com. app. util. ZYJAsyncTask; import com. app. util. ZYJCallBack; import android. app. activity; import android. OS. bundle; public class MainActivity extends Activity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); ZYJAsyncTask zyjAsyncTask = new ZYJAsyncTask (); zyjAsyncTask. setCallBackListener (new ZYJCallBack () {@ Override public void start () {System. out. println ("ssss started");} @ Override public void progress (Integer progress) {System. out. println ("ssss progress:" + progress) ;}@ Override public void dataResult (String resultString) {System. out. println ("ssss Result:" + resultString) ;}}); zyjAsyncTask.exe cute ("");}}
4. Running result
Ssss started
Ssss progress: 10
Ssss progress: 20
Ssss progress: 50
Ssss progress: 100
The result of ssss is: Hahaha, the operation is complete.