为了将数据从服务传回活动,我开始了解ResultReceiver、广播/本地广播和绑定服务。但是我对这种方法感到困惑:如果我们简单地调用活动静态公共函数来传递一些东西,那么这种方法的优缺点是什么。说我有活动:
public interface ListenerInterface {
void DataExchange(String data);
}
public class MainActivity extends Activity implements ListenerInterface{
private static MainActivity instance;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance=this;
Intent i=new Intent();
i.setClass(this, MyService.class);
startService(i);
}
public static MainActivity getInstance(){
if(instance!=null)
return instance;
return null;
}
@Override
public void DataExchange(String data) {
// TODO Auto-generated method stub
Log.d("sohail","data received="+data);
}
}
和一个 IntentService:
public class MyService extends IntentService{
MainActivity obj;
public MyService() {
super("MyService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
MainActivity.getInstance().DataExchange("Service Data");
}
}