android - 无法在未调用Looper.prepare()

时间:2015-06-11 16:51:06

标签: android android-service

我的服务中有一个asyncTask。它每10秒调用一次asyncTask。问题是我有时会收到此错误并且应用程序c 我在我的服务中要求asyncTask,它每10秒运行一次以检查一些数据。有时我会收到此错误:

    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)

这是我的服务代码:

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) {

                    }
                }

            }
        }
    }

}

我做错了什么?

谢谢

0 个答案:

没有答案