绑定到服务的客户端代码,通常在活动类中;我正在尝试将它移动到服务类,以便活动类尽可能干净和小。
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Bind to service with this line only:
AService.bindService(this);
}
}
public class AService extends Service {
public String test = "I want to see this";
public static AService aService;
private static boolean isBound;
private static Context context;
// ... IBinder, onBind etc also here on service side
public static void bindService(Context context) {
try {
Log.i(TAG, "bindService Start");
if (!isBound && context != null) {
Log.i(TAG, "Binding");
context.bindService(new Intent(context, AService.class),
serviceConnection, Context.BIND_AUTO_CREATE);
isBound = true;
Log.i(TAG, "Bound");
}
} catch (Exception e) {
Log.e(TAG, "bindService", e);
}
}
private static ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
try {
Log.i(TAG, "onServiceConnected Start");
aService = ((AService.LocalBinder) service).getService();
if (aService != null)
Log.i(TAG, aService.test);
Log.i(TAG, "onServiceConnected Finish");
} catch (Exception e) {
Log.e(TAG, "onServiceConnected", e);
}
}
public void onServiceDisconnected(ComponentName className) {
try {
Log.i(TAG, "onServiceDisconnected");
aService = null;
} catch (Exception e) {
Log.e(TAG, "onServiceDisconnected", e);
}
}
};
public static void unbind() {
try {
Log.i(TAG, "unbind start");
if (isBound && context != null) {
Log.i(TAG, "Unbinding");
context.unbindService(serviceConnection);
isBound = false;
context = null;
Log.i(TAG, "Unbound");
}
} catch (Exception e) {
Log.e(TAG, "unbind", e);
}
}
}
日志显示所有内容:
...
Bound
我做错了什么?
答案 0 :(得分:0)
这是
AService.bindService(this);
比这更好?
bindService(new Intent(context, AService.class),
serviceConnection, Context.BIND_AUTO_CREATE);
ServiceConnection实现在Activity中真的很烦人吗?我不信。
我没有看到任何一点将所有内容集中到Service中,然后在实际Service中调用静态方法以从Activity启动此Service。最佳做法是遵循Google推荐的标准方式,通过这样做,在您阅读代码时(如果您在团队中工作),您的代码会模糊不清并使其他人感到困惑。这对IMO没有任何意义。
我宁愿考虑更多关于如何将业务逻辑与活动隔离开来并将其集中到服务中,而不是将所有精力都放在隔离服务的每一项服务上,而是让Activity更多地关注UI内容。
真的希望能帮到你。