我遇到的问题是我不知道如何从服务中获取返回值。为什么我想要从服务返回值是我想在活动页面中显示这个返回值。以下是我的服务文件,返回值是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();
}
}
据我所知,服务与活动通信的常用方式是播送.
您可以通过以下方式在您想要“返回 retvalue”的位置发送广播:
Intent retIntent = new Intent(ServiceReturnIntent);
retIntent.putExtra("retvalue", retvalue);
sendBroadcast(retIntent);
其中ServiceReturnIntent和“retvalue”都是自定义的字符串,用于标识广播和值名称。
在您希望捕获返回值的活动中,您应该有一个广播接收器,其中包含以下内容:
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
......
}
}
你可以阅读本教程 http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html有关 Android 中广播的更多信息。
EDIT修改示例代码并将其设置为文本视图
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)