我遇到了一个问题,我不知道如何从服务中获取返回值。为什么我想要服务的返回值是我想在 Activity 页面中显示这个返回值。以下是我的服务文件,返回值是retvalue。
public class SyncService extends Service{
private String forSync, lastrecordfromlocal, userdefined;
DatabaseUtil dbUtil = new DatabaseUtil(this);
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
forSync = common.getInfoForSync(this);
String[] getlist = forSync.split(":");
lastrecordfromlocal = getlist[0].toString();
userdefined = getlist[1].toString();
if (common.isNetAvailable(this) == true) {
SyncServiceTask InstallData = new SyncServiceTask(this);
try {
String (((retvalue))) = InstallData.execute(lastrecordfromlocal, userdefined).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
this.stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
最佳答案
据我所知,服务与 Activity 通信的常用方式是BROADCAST。
您可以在您想要“返回返回值”的位置发送广播,例如:
Intent retIntent = new Intent(ServiceReturnIntent);
retIntent.putExtra("retvalue", retvalue);
sendBroadcast(retIntent);
其中ServiceReturnIntent和"retvalue"都是自定义的字符串,用来标识广播和值名。
在你希望捕捉返回值的 Activity 中,你应该有一个广播接收器,像这样:
public class myActivity extends Activity implements BroadcastReceiver {
TextView myTextView;
@Override
OnCreate(Bundle savedInstanceState) {
setContentView(R.layout.simple_layout);
myTextView = (TextView) findViewByID(R.id.simple_textview);
}
@Override
public void onReceive(Context context, Intent intent) {
int action = jumpTable.get(intent.getAction());
switch (action) {
case ServiceReturnIntent:
String valueFromService = intent.getStringExtra("retvalue");
myTextView.setText(valueFromService);
break;
// handle other action
......
}
}
您可以阅读 this tutorial有关在 android 中广播的更多信息。
编辑 通过将其设置为 TextView 来修改示例代码
关于android - 我怎样才能从android服务获得返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19042007/