0

所以我想要做的是每 X 秒/分钟/小时/任何时间在服务中执行 JSON 读取。当我尝试这段代码时,它不起作用,给了我这样的错误:http: //i.stack.imgur.com/nGkZR.png 我对 Android 开发很陌生。

public class MyService extends Service {
    static final int UPDATE_INTERVAL = 5000;
    Timer timer = new Timer();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        repeat();
        return START_STICKY;
    }

    private void repeat() {
        // TODO Auto-generated method stub
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                new ReadJSONFeedTask().execute("url");
            }
        }, 0, UPDATE_INTERVAL);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    String[] from = new String[] { "name", "time" };
    int[] to = new int[] { R.id.eventName, R.id.eventTime };
    List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> map;

    private String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return readJSONFeed(urls[0]);
        }

        protected void onPostExecute(String result) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                Log.i("JSON",
                        "Number of events: " + jsonArray.length());
                //call fillMaps.clear so that listview does not multiply, but a fresh
                //one starts instead
                fillMaps.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                //  events[i]=jsonObject.getString("title");
                    map = new HashMap<String, Object>();
                    map.put("name", jsonObject.getString("title"));
                    map.put("time", jsonObject.getString("date"));
                    fillMaps.add(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("s", "THE MAP: " + fillMaps);
            // called after json is finished parsing
        }
    }

}

AsyncTask 的打印堆栈跟踪

> 10-04 07:17:37.749: D/AndroidRuntime(12922): >>>>>> AndroidRuntime
> START com.android.internal.os.RuntimeInit <<<<<< 10-04 07:17:37.749:
> I/AndroidRuntime(12922): Heap size: -Xmx24m 10-04 07:17:37.749:
> D/AndroidRuntime(12922): CheckJNI is OFF 10-04 07:17:38.039:
> D/AndroidRuntime(12922): Calling main entry com.android.commands.pm.Pm
> 10-04 07:17:38.049: D/AndroidRuntime(12922): Shutting down VM 10-04
> 07:17:38.079: D/dalvikvm(12922): GC_CONCURRENT freed 103K, 70% free
> 308K/1024K, external 0K/0K, paused 1ms+8ms 10-04 07:17:38.079:
> I/AndroidRuntime(12922): NOTE: attach of thread 'Binder Thread #3'
> failed 10-04 07:17:38.079: D/jdwp(12922): Got wake-up signal, bailing
> out of select 10-04 07:17:38.079: D/dalvikvm(12922): Debugger has
> detached; object registry had 1 entries 10-04 07:17:38.339:
> D/AndroidRuntime(12932): >>>>>> AndroidRuntime START
> com.android.internal.os.RuntimeInit <<<<<< 10-04 07:17:38.339:
> I/AndroidRuntime(12932): Heap size: -Xmx24m 10-04 07:17:38.339:
> D/AndroidRuntime(12932): CheckJNI is OFF 10-04 07:17:38.629:
> D/AndroidRuntime(12932): Calling main entry com.android.commands.am.Am
> 10-04 07:17:38.639: I/ActivityManager(179): Force stopping package
> lv.exs.exsnotikumi uid=10085 10-04 07:17:38.649: I/Process(179):
> Sending signal. PID: 12911 SIG: 9 10-04 07:17:38.649:
> W/ActivityManager(179): Scheduling restart of crashed service
> lv.exs.exsnotikumi/.MyService in 5000ms 10-04 07:17:38.649:
> I/ActivityManager(179):   Force finishing activity
> HistoryRecord{40959810 lv.exs.exsnotikumi/.Main} 10-04 07:17:38.659:
> E/InputDispatcher(179): channel '40929d98
> lv.exs.exsnotikumi/lv.exs.exsnotikumi.Main (server)' ~ Consumer closed
> input channel or an error occurred.  events=0x8 10-04 07:17:38.659:
> E/InputDispatcher(179): channel '40929d98
> lv.exs.exsnotikumi/lv.exs.exsnotikumi.Main (server)' ~ Channel is
> unrecoverably broken and will be disposed! 10-04 07:17:38.669:
> I/WindowManager(179): WIN DEATH: Window{40929d98
> lv.exs.exsnotikumi/lv.exs.exsnotikumi.Main paused=true} 10-04
> 07:17:38.669: I/ActivityManager(179):   Force stopping service
> ServiceRecord{4096f970 lv.exs.exsnotikumi/.MyService} 10-04
> 07:17:38.689: D/VoldCmdListener(124): volume shared /mnt/sdcard ums
> 10-04 07:17:38.699: I/ActivityManager(179): Starting: Intent {
> act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER]
> flg=0x10000000 cmp=lv.exs.exsnotikumi/.Main } from pid 12932 10-04
> 07:17:38.709: D/AndroidRuntime(12932): Shutting down VM 10-04
> 07:17:38.709: I/ActivityManager(179): Start proc lv.exs.exsnotikumi
> for activity lv.exs.exsnotikumi/.Main: pid=12940 uid=10085 gids={3003}
> 10-04 07:17:38.719: D/dalvikvm(12932): GC_CONCURRENT freed 103K, 69%
> free 327K/1024K, external 0K/0K, paused 1ms+1ms 10-04 07:17:38.729:
> W/InputManagerService(179): Got RemoteException sending
> setActive(false) notification to pid 12911 uid 10085 10-04
> 07:17:38.749: I/AndroidRuntime(12932): NOTE: attach of thread 'Binder
> Thread #3' failed 10-04 07:17:38.749: D/jdwp(12932): Got wake-up
> signal, bailing out of select 10-04 07:17:38.749: D/dalvikvm(12932):
> Debugger has detached; object registry had 1 entries 10-04
> 07:17:38.799: W/IInputConnectionWrapper(238): showStatusIcon on
> inactive InputConnection 10-04 07:17:38.859: W/ActivityThread(12940):
> Application lv.exs.exsnotikumi is waiting for the debugger on port
> 8100... 10-04 07:17:38.869: I/System.out(12940): Sending WAIT chunk 10-04 07:17:38.899: I/dalvikvm(12940): Debugger is active 10-04
> 07:17:39.069: I/System.out(12940): Debugger has connected 10-04
> 07:17:39.069: I/System.out(12940): waiting for debugger to settle...
> 10-04 07:17:39.269: I/System.out(12940): waiting for debugger to
> settle... 10-04 07:17:39.359: W/ActivityManager(179): Activity pause
> timeout for HistoryRecord{40aa20b0 lv.exs.exsnotikumi/.Main} 10-04
> 07:17:39.469: I/System.out(12940): waiting for debugger to settle...
> 10-04 07:17:39.669: I/System.out(12940): waiting for debugger to
> settle... 10-04 07:17:39.879: I/System.out(12940): waiting for
> debugger to settle... 10-04 07:17:40.079: I/System.out(12940): waiting
> for debugger to settle... 10-04 07:17:40.279: I/System.out(12940):
> waiting for debugger to settle... 10-04 07:17:40.449:
> I/3gw.Service(642): Mobile Network not connected - not roaming 10-04
> 07:17:40.479: I/System.out(12940): waiting for debugger to settle...
> 10-04 07:17:40.679: I/System.out(12940): waiting for debugger to
> settle... 10-04 07:17:40.879: I/System.out(12940): waiting for
> debugger to settle... 10-04 07:17:41.079: I/System.out(12940): waiting
> for debugger to settle... 10-04 07:17:41.289: I/System.out(12940):
> debugger has settled (1496) 10-04 07:17:41.359: D/szipinf(12940):
> Initializing inflate state 10-04 07:17:41.489: D/dalvikvm(12940):
> GC_EXTERNAL_ALLOC freed 98K, 51% free 2685K/5379K, external 0K/0K,
> paused 46ms 10-04 07:17:41.569: W/dalvikvm(12940): Exception
> Ljava/lang/RuntimeException; thrown while initializing
> Landroid/os/AsyncTask; 10-04 07:17:41.689: I/ActivityManager(179):
> Displayed lv.exs.exsnotikumi/.Main: +2s990ms 10-04 07:17:41.699:
> W/IInputConnectionWrapper(12940): showStatusIcon on inactive
> InputConnection 10-04 07:17:43.219: D/dalvikvm(238): GC_CONCURRENT
> freed 452K, 48% free 3297K/6279K, external 792K/1100K, paused 5ms+8ms
4

1 回答 1

0

不是这个问题的真正答案,而是通过使用 ScheduledExecutorService 解决了

    ScheduledExecutorService scheduler =
            Executors.newSingleThreadScheduledExecutor();        
private void repeat() {
        // TODO Auto-generated method stub
        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                new ReadBackgroundJSONFeedTask().execute("url");
                Log.d("s", "json read!");
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }
于 2013-10-05T08:34:19.200 回答