2

我在我的 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;
}
.....
}

我不确定这是否是获得活页夹的正确方法。任何帮助深表感谢!!

4

2 回答 2

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;
        }
    };
于 2012-11-30T03:51:48.713 回答
0

Update your code

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;
}

.....

}
于 2012-11-30T03:37:31.527 回答