I am trying to use an SDK that seems to need to create a handler into my service.
A error message appeared saying that I can't create handler if the thread has not called Looper.prepare()
, so I do call Looper.prepare()
and this problem disappear.
However, this service need to start an activity after a while, and this Looper.prepare()
seems to be messing with it, as the first UI function crash saying that it cannot be called from a non-ui thread.
I am a bit confused about why this is happening, and the research I made on thread and looper didn't help me. I get why we cannot create a handler if a looper does not exist on the thread, but not why creating a looper prevent me from using the ui thread afterward.
Below my code simplified :
public class MyService extends Service implement SDKCallback{
...
void callSDK(){
Looper.prepare();
SDK.run(); //Does thing I don't know about
}
@Override
SDKCallback(){
startActivity(new Intent(this, MyActivity.class);
}
}
You dont have to call Looper.prepare()
. Try this code to create Handler
,
new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
}
};
If you put Looper.prepare()
in your worker thread, it will solve your first crash problem [the thread has not called Looper.prepare()
]. But its not in UI thread, so you cant start next Activity
.
What this above code does is, it creates the Handler
in UI thread. So you can start next Activity
.
Edit: Try this.
@Override
SDKCallback(){
new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
startActivity(new Intent(MyService.this, MyActivity.class));
}
};
}