Android : Android create handler inside thread into Service

on Monday, September 29, 2014


i'm writing simple android service and i want to use such as Toast or Notification but i get this error:



FATAL EXCEPTION: Thread-17116
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()


i can not use runOnUiThread . my service does not know that. for example i try to use that with : this, getBaseContect(), getApplication, mContext for .runOnUiThread(new Runnable() {}


i get problem and i can not resolve problem.


this is my code:



public class TsmsService extends Service {

private Timer smsThread;
private DatabaseHandler db;
private SQLiteDatabase dbHelper;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread(getBaseContext());
smsThread.scheduleAtFixedRate(getSMSThread, 0, 1000); //(timertask,delay,period)
return super.onStartCommand(intent, flags, startId);
}

public class GetSMSThread extends TimerTask {
private Context mContext;

public GetSMSThread(Context context) {
mContext = context;
}

@Override
public void run() {

this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplication() , "Service is Running ... " , Toast.LENGTH_SHORT).show();
}
});

}
}
}

0 comments:

Post a Comment