您的键盘没有响应,因为 displayResult 方法正在您的主 ui 线程上执行。
正确处理此问题的一种可能解决方案是使用IntentService,例如,您可以这样做:
MyIntentService.java
public class MyIntentService extends IntentService {
//Each of these results represent a possible status of your service
public static final int RESULT_ERROR = -1;
public static final int RESULT_ENDED = 1;
public static final int RESULT_START = 0;
public static final String SERVICE_BROADCAST = MyIntentService.class.getName()+".Broadcast";
public MigrateService(){
super(MigrateService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
//Get the query
String queryText = intent.getStringExtra("MyQuery");
//Notify the activity that search has started
publishResult(RESULT_START, Bundle.EMPTY);
Bundle data = null;
try{
data = getDataWithRetrofit(queryText);
} catch (SomeException e){
//In case of error, notify the activity
publishResult(RESULT_ERROR, Bundle.EMPTY);
}
//Search is ended
publishResult(RESULT_ENDED, data);
}
public void publishResult(int resultCode, Bundle data){
Intent intent = new Intent(SERVICE_BROADCAST);
intent.putExtras(data);
intent.putExtra("resultCode",resultCode);
sendBroadcast(intent);
}
}
基本上,您有一个Service,它在后台线程中获取数据并在某些事件发生(开始/结束)时将数据发送到您的Activity。
在您的 Activity 课程中,您需要执行以下操作:
1.声明一个BroadcastReceiver 实例:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra("resultCode")) {
int resultCode = intent.getIntExtra("resultCode",MyService.STATUS_ERROR);
switch (resultCode) {
case MyIntentService.RESULT_START:
showIndeterminateProgress();
break;
case MyIntentService.RESULT_ENDED:
updateResultList(data);
break;
case MyIntentService.RESULT_ERROR:
showErrorMessage();
break;
}
}
}
};
2。注册和注销您的BroadcastReceiver:
@Override
public void onResume(){
super.onResume();
registerReceiver(mReceiver, new IntentFilter(MyIntentService.SERVICE_BROADCAST));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
3.启动您的服务:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
@Override
public boolean onQueryTextChange(String newText)
{
if (!newText.trim().equals(""))
{
Intent i = new Intent(this, MyIntentService.class);
i.putExtra("MyQuery",newText);
startService(i);
return false;
}
}
});
来源: