android - 我怎样才能从android服务获得返回值

标签 android service

我遇到了一个问题,我不知道如何从服务中获取返回值。为什么我想要服务的返回值是我想在 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/

相关文章:

angular - 在模型类 Angular 中注入(inject)服务

android - 减少 Android 服务电池消耗的技巧?

android - 如何实现像 Lollipop 这样的联系人详细信息屏幕

android - 如何解决致命异常 : Timer-11 in android?

azure - 无法在 Azure 数据工厂中创建链接服务

wcf - WCF 中的服务契约是什么?

c# - 运行程序集的 .NET 调度程序?

service - 如果未使用批处理文件安装服务,如何在 Windows 中检查

android - 如何获取我上传文件的网站的网址?

java - 我们如何使用 Linear 布局来代替 ListView