2

BootReceiverクラスでブート完了インテントを受け取り、そのインテントを受け取ったときにサービスを開始します。

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

サービスは正常に開始されましたが、サービス内でバインダーオブジェクトを使用したいと思います。これがサービスコードです。

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

コードを更新する

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 に答える