Android:将参数从Activity传递给Service

标签 android binding service android-activity parameter-passing

我通过这种方式绑定(bind)到服务:

Activity 类:

ListenLocationService mService;
@Override
public void onCreate(Bundle savedInstanceState) {
        ...
        Intent intent = new Intent(this, ListenLocationService.class);
        intent.putExtra("From", "Main");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        ...
}

private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();         
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };

这是我的 ServiceonBind 方法:

@Override
public IBinder onBind(Intent intent) {
    Bundle extras = intent.getExtras(); 
    if(extras == null)
        Log.d("Service","null");
    else
    {
        Log.d("Service","not null");
        String from = (String) extras.get("From");
        if(from.equalsIgnoreCase("Main"))
            StartListenLocation();
    }
    return mBinder;
}

所以我在 LogCat 中有“null” - 尽管我在 bindService

之前创建了 intent.putExtra,但 bundle 为 null

一般服务工作正常。但是,我只需要从应用程序的主要 Activity 中调用 StartListenLocation(); (我决定通过发送标志来执行此操作)。

我如何向服务发送数据?或者还有其他方法可以检查 onBind 启动了什么 Activity ?

最佳答案

你可以通过这种简单的方式传递参数:-

Intent serviceIntent = new Intent(this,ListenLocationService.class); 
   serviceIntent.putExtra("From", "Main");
   startService(serviceIntent);

并在服务类的 onStart 方法中获取参数

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Bundle extras = intent.getExtras(); 
    if (extras == null) {
        Log.d("Service","null");
    else {
        Log.d("Service","not null");
        String from = (String) extras.get("From");
        if(from.equalsIgnoreCase("Main"))
        StartListenLocation();
    }
}

享受:)

关于Android:将参数从Activity传递给Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954878/

相关文章:

java - 带有涉及两个 DAO 的遗留代码的 Spring 事务

delphi - 服务应用程序中的 PostMessage

android - 如何在 Andengine 中的 Base Game Activity 上启用声音?

android - 如何在包含的布局和多个模型中管理数据绑定(bind)?

c# - 第 3 方库中的 MonoTouch 绑定(bind)通知

tfs - 更改 TFS 构建代理的身份

android - 无法解析 : pub. devrel :easypermissions:0. 3.0

android - Eclipse ADT facebook 设置 - 在平台工具中定位 adb 工具

android - map Android V2 : java. lang.noclassdefounderror : com. google.android.gms.R$styleable

silverlight - 在 Silverlight 应用程序中调用 SetBinding() 两次?