I want to do some long operation (like copying/loading file) when the application is created. I created a thread to do so, that thread DOES NOT update UI. I got an error saying cannot create handler in a thread without calling Looper.prepare(). What’s wrong with my code?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
threadFileManager = new Thread (
new Runnable() {
public void run() {
FileManager fM = new FileManager();
fM.copyFileFromAssetToStorage();
}
});
threadFileManager.start();
}
Edit:The error lied in my FileManager class, when it was a subclass of Activity. Changing to Service worked.
The
Applicationclass is the wrong place to do this. If you want, it’s acceptable to use theApplication‘sonCreate()method to start aService. You should implement this background thread in aService, as the purpose ofServiceis to do things in the background. TheApplicationclass should seldom be used. It’s a last resort for maintaining minimal amounts of global state.Once you move this code into a
Service,Looper.prepare()will already have been called for you by Android.EDIT:
OP was actually trying to create a Handler inside of the Thread when he invoked the constructor of his FileManager class. While my comment above is still true, it is not relevant to OP’s question as he was subclassing Activity and not Application.
To be clear, the actual problem was that he was creating a Handler inside a Thread which had not yet called Looper.prepare() (via new FileManager()). The correct fix would be to create the Handler on the main thread, i.e. in one of the Activity or Service callbacks.