android -Can't create handler inside thread that has not called Looper.prepare()

493 views Asked by At

I have an asyncTask in my services . It calls for an asyncTask every 10 seconds . The problem is I got this error sometimes and app c i'm calling for an asyncTask in my services , it runs every 10 second for checking some data. Some times I get this error :

    Services_chat$1.run(Services_chat.java:50)
    at java.util.Timer$TimerImpl.run(Timer.java:284)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:121)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
    at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
    ... 2 more
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:121)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
    at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
    at ir.radaar.goblin.Services_chat$1.run(Services_chat.java:50)
    at java.util.Timer$TimerImpl.run(Timer.java:284)

this is my service code :

public class Services_chat extends Service {
    Boolean runCode = false,finished=false;;
    SharedPreferences settings;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        runCode = true;
        settings = getSharedPreferences("settings", MODE_PRIVATE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

                    new Timer().scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            if (runCode) {
                                try {
                                    new GetChat().execute();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }, 0, 10000);// put here time 1000 milliseconds=1 second
        return Service.START_STICKY;
    }


    public class GetChat extends AsyncTask<Void, Void, Void> {
        private static final String TAG_CONTACTS = "contacts";
        JSONArray contacts = null;
        SharedPreferences settings;
        DatabaseHandler db;

        long when;
        Random rd;
        int randomid = 0, icon = 0;
        String alarmText = "", titles = "";
        String usernameFrom = "", msg = "";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            try {
                settings = getSharedPreferences("settings", MODE_PRIVATE);
                db = new DatabaseHandler(Services_chat.this);
                if (!db.isOpen())
                    db.open();

                runCode=false;
            } catch (Exception e) {
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            Spots_tab1_json sh = new Spots_tab1_json();
            String jsonStr = sh.makeServiceCall(
                    "http://url.com/getUnreadChat.php?userTo=" + settings.getString("username", ""),
                    Spots_tab1_json.GET);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        msg = new String(c.getString("msg").getBytes("ISO-8859-1"), "UTF-8");
                        usernameFrom = new String(c.getString("from").getBytes("ISO-8859-1"), "UTF-8");
                        randomid = Integer.parseInt(new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
                        db.insertUnreadChat(randomid);
                        db.insertChat(msg, "", usernameFrom, settings.getString("username", ""));
                    }

                } catch (Exception e) {
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            runCode=true;
            if (contacts != null) {
                if (contacts.length() > 0) {
                    try {
                        if (contacts.length() > 0) {
                            // ///////////////hide notification manager/////////
                            NotificationManager notifies2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            notifies2.cancelAll();

                                rd = new Random();
                                icon = R.drawable.ic_launcher;
                                NotificationManager notifies = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                                Intent notifyIntent = new Intent(Services_chat.this, Chat.class);
                                notifyIntent.putExtra("username", usernameFrom);
                                PendingIntent pendingintent = PendingIntent.getActivity(Services_chat.this, 0,
                                        notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                                when = System.currentTimeMillis();
                                Notification notification = new Notification(icon, msg, when);
                                notification.setLatestEventInfo(Services_chat.this, Z_Farsi.Convert("گفنگوی جدید"),
                                        msg, pendingintent);
                                notifies.notify(randomid, notification); 

                                Uri not = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), not);
                                r.play();

                        }
                    } catch (Exception e) {

                    }
                }

            }
        }
    }

}

What am I doing wrong ?

Thanks

0

There are 0 answers