- Home /
Can't start a Handler on the main thread
I'm working on a .jar api to read Google Fit data from Unity3D. The problem that I'm facing right now is that when I want to execute this block of code:
private void buildFitnessClient() { mClient = new GoogleApiClient.Builder(myContext).addApi(Fitness.HISTORY_API) .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE)) .addConnectionCallbacks(new ConnectionCallbacksListener()) .enableAutoManage(this, 0, new ConnectionFailedListener()).build(); }
I get the error: java.lang.IllegalStateException: Must be called from main thread of process
This error is due to the this reference in the last sentence of the line of code.
Now online I found that I could fix this by starting a Handler on the Main Looper, I tried this with this code:
new Handler(Looper.getMainLooper()).post( new Runnable() { @Override public void run() { try { buildFitnessClient(); } catch (Exception ex) { Log.i(TAG, ex.getMessage() + "\n"); } } });
For some reason my Unity app instantly crashes, usually I can get the error since I use a try catch statement. With this problem it instantly crashes and there is no log I can check.
When I create my Handler without the mainlooper, like:
new Handler()
or
new Handler(Looper.myLooper())
The code runs, but the java.lang.IllegalStateException error remains, and the Thread.currentThread() obviously remains the same.
The thread that the program runs on is a thread created by Unity.
Thanks in advance!
the program crashes on 'this' in the enableAuto$$anonymous$$anage(this, 0, ....
It seems like the thread starter works, it crashes on the method that builds the fitness client?