从服务检索数据到活动OnResume()

本文关键字:OnResume 活动 服务 检索 数据 | 更新日期: 2024-09-24 02:58:11

我遇到一个问题已经有一段时间了。我的活动启动并使用活动OnPause()中的ServiceName.PutExtra(name,value)向我的服务发送数据(DT开始、DT结束、Char操作),但它也需要读取相同的新值。

该活动使用GPS记录设备何时移动和何时不移动,以及这些移动的开始和结束时间。

当我返回到我的活动OnResume()需要读入服务当前记录的内容时,请继续此记录并停止服务。

我读了很多关于绑定服务的文章,但无法使用带有解释的简单代码示例(来源于@Xamarin网站、android开发者网站、stackoverflow)

有人能给我看一段代码吗?其中明确说明了服务活动之间的绑定,以及如何将数据从服务获取到活动OnResume()中??

我使用Xamarin和C#,但如果需要,我可以从java代码中进行调整

从服务检索数据到活动OnResume()

我已经很长时间没有使用它了(因为我现在正在使用LocalBroadcasts),所以我可能会错过一些东西,但一般来说,它会是这样的(在java中):

活动中:

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder service) {
    LocalBinder binder = (LocalBinder) service;
    mStateChecker = binder.getService();
    mBound = true;
    Intent intent2 = getIntent();
    finish();
    startActivity(intent2); 
}

public void onServiceDisconnected(ComponentName arg0) {
     mBound = false;
     Intent intent2 = getIntent();
     finish();
     startActivity(intent2);
    }   
};


 //start the service & bind to it
    startService(new Intent(this, StateChecker.class));
    Intent intent = new Intent(this, StateChecker.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 

在役:

@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}
/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    StateChecker getService() {    //  StateChecker is the name of this class
        // Return this instance of LocalService so clients can call public methods
        return StateChecker.this;
    }
}