gpt4 book ai didi

android - 无法从服务中获取 Binder 对象

转载 作者:行者123 更新时间:2023-11-29 01:59:03 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于android - 无法从服务中获取 Binder 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com