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();
}
});
}
}
}
Try creating a Handler in onStartCommand (so, from the UI thread). Then use that Handler to trigger the Toast. For example:
private Handler mToastHandler = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
mToastHandler = new Handler();
...
}
...
// from inside your child thread
mToastHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(...);
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments