【发布时间】:2015-09-12 01:54:06
【问题描述】:
我正在尝试从另一个类 (BaseExpandableListAdapter) 调用活动中的方法。 Activity 中的方法启动一个服务并调用 bindService(,,) 方法。但是 bindService 方法总是返回 false。我检查了其他类似的帖子,但没有一个能解决我的问题。非常感谢任何评论。
这是我在活动中调用方法的 BaseExpendableListAdapter 类:
class myExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, String> _listDataChild;
private TextView myroutes_distance=null;
private TextView myroutes_time=null;
private TextView myroutes_speed=null;
public myExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, String> 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
}
这里是带有 continue 方法的 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() 方法时,绑定失败。
【问题讨论】:
-
为什么要在 getChildView() 中实例化 MainActivity?
-
好吧,否则,我无法从另一个活动中引用 MyActivity 中的 continue 方法。
-
首先,您不应该从其他活动中调用该方法,在适配器中您有对该活动的引用,它是
_context。其次,您应该永远不要自行实例化活动。 -
那你觉得我应该怎么做?我需要从 MyActivity 类启动服务,进程从 myExpandableListAdapter 类开始。对不起,如果我的问题含糊不清!
-
可能是 LocalBroadCastManager?
标签: android android-activity android-service android-service-binding