Android开发之通过接口回调机制加载数据的简单实现,在实际开发中通过callback方法得到网络加载的数据的使用频率远比通过直接开启线程或异步任务加载数据的频率高的多,这篇文章的代码将简单实现该机智的调用,体会下callback的精髓。
MainActivity的代码
package com.example.f07_callback01; import com.example.f07_callback01.A.Callback; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub A getString=new A(); //通过调用接口得到数据 getString.loadString("", new Callback() { @Override public void get(String result) { // TODO Auto-generated method stub Log.i("TAG", "-------->"+result); } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
回调接口类的方法
package com.example.f07_callback01; public class A { //模拟从服务器端得到字符串 public void loadString(String path,final Callback callback){ new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub String msg="通过接口调用数据"; callback.get(msg); } }).start(); } public interface Callback{ public void get(String result); } }