无法从Service获取binder对象

时间:2012-11-30 03:25:26

标签: android android-service

我在BootReceiver类中收到启动完成的意图,并在收到该意图时启动服务。

@Override
public void onReceive(Context arg0, Intent arg1) {
    Intent myIntent = new Intent(arg0, BootService.class);
    arg0.startService(myIntent);    
}

服务正常启动,现在,我想在服务中使用binder对象。这是服务代码。

public class BootService extends Service implements IBinder{
private IBinder binder;

public class LocalBinder extends Binder {
    IBinder getService() {
        return BootService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    Log.d("BootService", "onCreate()");

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("BootService", "onStartCommand()");
    binder = new LocalBinder().getService();
    //This doesn't seem to work
    //I wana use this binder object here

    return START_STICKY;
}
.....
}

我不确定这是否是获取活页夹的正确方法。 非常感谢任何帮助!!

2 个答案:

答案 0 :(得分:1)

In ur Acivity 
@Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent(getApplicationContext(), MyService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mConnection);
    }



    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {

        Toast.makeText(getApplicationContext(), "Service disconnected", 1000).show();
        mBindr = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(getApplicationContext(), "Service connected", 1000).show();
            LocalBinder mLocalBinder = (LocalBinder) service;
            myService = mLocalBinder.getSrvice();
            mBindr = true;
        }
    };

答案 1 :(得分:0)

更新您的代码

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BootService extends Service {
    private IBinder binder = new LocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return binder;
}

public class LocalBinder extends Binder {
    BootService getService() {
        return BootService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    Log.d("BootService", "onCreate()");

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("BootService", "onStartCommand()");
    //binder = new LocalBinder().getService();
    //This doesn't seem to work
    //I wana use this binder object here

    return START_STICKY;
}

.....

}