主线程exception上的Android Bump Api网络

首先,我对Android和JAVA世界都很陌生(来自C / C ++ / Objective-C)。 我正在尝试集成Android bump API(3.0,最新版本),但我遇到了麻烦。 我复制了这个例子,它在Android 2.2下工作正常,碰撞服务正确启动,但对于Android 3.0及其上层它不起作用。 在加载我的活动时,我有一个exception(主线程上的网络),我知道这个exception以及如何避免它,但在这种情况下,Bump表示他们在自己的线程中运行他们的API所以我不这样做真的知道我为什么得到它。 他们说你不需要运行一个线程或任务。

以下是我的活动示例

public class BumpActivity extends Activity { private IBumpAPI api; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bump); bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE); IntentFilter filter = new IntentFilter(); filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED); filter.addAction(BumpAPIIntents.DATA_RECEIVED); filter.addAction(BumpAPIIntents.NOT_MATCHED); filter.addAction(BumpAPIIntents.MATCHED); filter.addAction(BumpAPIIntents.CONNECTED); registerReceiver(receiver, filter); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder binder) { Log.i("BumpTest", "onServiceConnected"); api = IBumpAPI.Stub.asInterface(binder); try { api.configure("API_KEY", "Bump User"); } catch (RemoteException e) { Log.w("BumpTest", e); } Log.d("Bump Test", "Service connected"); } @Override public void onServiceDisconnected(ComponentName className) { Log.d("Bump Test", "Service disconnected"); } }; } 

听起来好像在api.configure上的连接服务期间出现问题….我应该在一个单独的线程中运行它还是在它自己的AsynchTask中运行它,但那么如何以及为什么?

我在这个问题上坚持了一天左右……在发布它之后2分钟我就解决了这个问题……我只是把api.configure放在一个单独的线程上(比AsynchTask短)。

 private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder binder) { Log.i("BumpTest", "onServiceConnected"); api = IBumpAPI.Stub.asInterface(binder); new Thread() { public void run() { try { api.configure("API_KEY", "Bump User"); } catch (RemoteException e) { Log.w("BumpTest", e); } } }.start(); Log.d("Bump Test", "Service connected"); } @Override public void onServiceDisconnected(ComponentName className) { Log.d("Bump Test", "Service disconnected"); } }; 

在后台流程中提出请求。

主线程上的网络有一个exception发生在2.2及3.0以上版本,区别在于3.0及以上它们会强制你将涉及一些重或慢操作的所有内容放在不同的线程中,正如你在asyncTask中所说的那样。

你只需要创建一个内部的asyncTask,并在其onBackground方法中放入你的api.configure 🙂

 class LoadBumpAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { try { api.configure("9b17d663752843a1bfa4cc72d309339e", "Bump User"); } catch (RemoteException e) { Log.w("BumpTest", e); } return null; } } 

只需在连接的服务上调用new LoadBumpAsyncTask().execute()