Reputation: 1135
In my android application, I am sending messages to contacts.. and it is showing " This handler class should be static or else might be leak". My application is crashing in Mobile phone but it is working in Emulator, I am giving the code below pls go through it and any error if anybody can help please help..
progresshandler = new Handler()
{
public void handleMessage(Message msg)
{
//progressDialog.dismiss();
//Toast.makeText(SendMessagesActivity.this, "Messages Sent",Toast.LENGTH_LONG).show();
new ProgressTask().execute();
}
};
Upvotes: 1
Views: 163
Reputation: 11464
To avoid leaking Handler create Custom class that extends Handler class as below :
// Handler of incoming messages from clients.
private static class IncomingHandler extends Handler {
private WeakReference<YourActivity> yourActivityWeakReference;
public IncomingHandler(YourActivity yourActivity) {
yourActivityWeakReference = new WeakReference<>(yourActivity);
}
@Override
public void handleMessage(Message message) {
if (yourActivityWeakReference != null) {
YourActivity yourActivity = yourActivityWeakReference.get();
Edited : new ProgressTask().execute();
// switch (message.what) {
// }
}
}
}
Create object of this class wherever you want to use as below.
private IncomingHandler mPulseHandler;
mPulseHandler = new IncomingHandler(HomeActivity.this);
mPulseHandler.sendEmptyMessage(0);
Edited :
IncomingHandler progresshandler = new IncomingHandler(YourActivity.this);
if (editMessage.getText().toString().length() > 0) {
SendMessagesThread thread = new SendMessagesThread(progresshandler);
thread.start();
// progressDialog.show();
}
Edited :
Declare this task in your activity :
private ProgressTask progressTask;
Create instance of it in onCreate()
progressTask=new ProgressTask();
Change line in IncomingHandler :
yourActivity.progressTask.execute();
Thanks
Upvotes: 1