大家好,又见面了,我是你们的朋友全栈君。
我想从另一个类(BaseExpandableListAdapter)的活动中调用一个方法。活动中的方法启动服务并调用bindService(,,)方法。但是,bindService方法总是返回false。我查了其他类似的帖子,但没有一个解决了我的问题。任何评论非常感谢。Android bindservice方法返回false
这里是BaseExpendableListAdapter类中,我调用该方法的活动:
class myExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap _listDataChild;
private TextView myroutes_distance=null;
private TextView myroutes_time=null;
private TextView myroutes_speed=null;
public myExpandableListAdapter(Context context, List listDataHeader,
HashMap listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, final ViewGroup parent) {
MyActivity myactivity = new MyActivity();
myactivity.continue(_context.getApplicationContext()); // continue is the method that I’m calling which is within the activity
}
这里与方法继续活动:
public class MyActivity extends FragmentActivity implements
MyService.Callbacks{
boolean isBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void continue(Context ctx){
current_intent = new Intent(ctx.getApplicationContext(), MyService.class);
ctx.getApplicationContext().startService(current_intent); // This method works fine.
isBound = ctx.getApplicationContext().bindService(current_intent, mConnection, Context.BIND_AUTO_CREATE); // Here is where I have problem. isBound is always false.
}
public ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,IBinder service) {
//
Myservice.LocalBinder binder = (MyService.LocalBinder) service;
myservice = binder.getServiceInstance(); //Get instance of your service!
myservice.registerClient(MyActivity.this); //Activity register in the service as client for callabcks!
}
}
public void setup(){
current_intent = new Intent(MyActivity.this, MyService.class);
startService(current_intent);
isBound = bindService(current_intent, mConnection, Context.BIND_AUTO_CREATE);
// both startService and bindService methods work fine here.
}
}
请注意,我用setup()方法中的类似命令,它工作得很好,但是当我在continue()方法中使用bindservice()方法时,绑定失败。
+0
你为什么在getChildView实例在MainActivity()? –
+0
那么因为否则,我无法从其他活动中引用MyActivity中的继续方法。 –
+1
首先,您不应该从其他活动中调用该方法,而是在引用该活动的适配器中,它是’_context’。其次,你应该从不**自己实例化活动。 –
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/140606.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...