使AsyncTask静态(有问题,提供代码)

时间:2012-03-08 23:14:34

标签: android

我需要知道如何从该活动启动的服务启动我原始活动中的AsyncTask。它可以获取音乐并在服务中播放它,我希望它在完成之后抓住下一首歌:

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() 
    {           
        public void onCompletion(MediaPlayer mp) 
        {               
            if (MainMenu.radioFlag == 1) {
                // Start new asynctask
            } else {
            stopSelf();
            }
        }           
    });

下面是我的Radio.class中的AsyncTask。我不知道如何通过引用Radio.this使其静态,我也在startService(i)和stopService(i)上遇到错误。我非常感谢你的帮助,谢谢。

private class LoadList extends AsyncTask<String, UserRecord, JSONArray> {

    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    JSONArray jArray;

    @Override
    protected void onCancelled() {
        Toast toast = Toast.makeText(getApplicationContext(), "Loading failed, trying again", Toast.LENGTH_LONG);
        toast.show();
        new LoadList().execute(linkurl);
    }

    protected JSONArray doInBackground(String... link) {

        linkurl = link[0];
        URI uri = null;
        try {
            uri = new URI(link[0]);
        } catch (URISyntaxException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(uri);
            //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }

        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        if (result == null) {
            linkurl = link[0];
            cancel(true);                   
        } else {

        try{
            jArray = new JSONArray(result);
            JSONObject json_data=null;

            displayname = new String[jArray.length()];
            song_name = new String[jArray.length()];
            artist = new String[jArray.length()];
            description = new String[jArray.length()];
            genre = new String[jArray.length()];
            custom_genre = new String[jArray.length()];
            album = new String[jArray.length()];
            timestamp = new String[jArray.length()];
            song_id  = new String[jArray.length()];
            avatar = new String[jArray.length()];
            test_rating = new Float[jArray.length()];
            songurl = new String[jArray.length()];
            viewss = new String[jArray.length()];
            section = new String[jArray.length()];
            plays = new String[jArray.length()];
            downloads = new String[jArray.length()];
            ratingcount = new String[jArray.length()];
            commentcount = new String[jArray.length()];
            dlFlag = new int[jArray.length()];
            link1 = new String[jArray.length()];
            link2 = new String[jArray.length()];
            link3 = new String[jArray.length()];
            link4 = new String[jArray.length()];
            link5 = new String[jArray.length()];

            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                song_id[i]=json_data.getString("id");
                song_name[i]=json_data.getString("songname");
                artist[i]=json_data.getString("artist");
                displayname[i]=json_data.getString("displayname");
                description[i]=json_data.getString("description");
                genre[i]=json_data.getString("genre");
                custom_genre[i]=json_data.getString("customgenre");
                album[i]=json_data.getString("album");
                timestamp[i]=json_data.getString("format");
                avatar[i]=json_data.getString("image_url");
                songurl[i]=json_data.getString("song_url");
                test_rating[i] = (float) json_data.getDouble("rating");
                viewss[i] = json_data.getString("views");
                section[i] = json_data.getString("section");
                plays[i] = json_data.getString("plays");
                downloads[i] = json_data.getString("downloads");
                ratingcount[i] = json_data.getString("rating_count");
                commentcount[i] = json_data.getString("comments");
                dlFlag[i] = json_data.getInt("downloadflag");
                link1[i] = json_data.getString("link1");
                link2[i] = json_data.getString("link2");
                link3[i] = json_data.getString("link3");
                link4[i] = json_data.getString("link4");
                link5[i] = json_data.getString("link5");                
            }
        }
        catch(JSONException e1){
            e1.printStackTrace();

        } catch (ParseException e1) {
            e1.printStackTrace();
        }           
        }
        return null;
    }

    protected void onProgressUpdate(UserRecord... progress) {

    }

    protected void onPostExecute(JSONArray jArray) {                                                                            
        i.putExtra("songURL", songurl[0]);
        i.putExtra("songNAME", displayname[0]);

        MainMenu.radioFlag = 1;

        ratingBar.setRating(0);

        tvTrack.setText(displayname[0]);

        if(dialog.isShowing()) {
            dialog.dismiss();
            }
        if(MainMenu.serviceRunning == 1) {
            stopService(i); 
            startService(i);
        } else {
            startService(i);
        }

        tvTime.setText(timestamp[0]);
        tvViews.setText(viewss[0]);
        tvComments.setText(commentcount[0]);
        tvRatings.setText(ratingcount[0]);
        tvPlays.setText(plays[0]);
        tvDownloads.setText(downloads[0]);

        if(description[0] == "null" || description[0] == ""){                                                               
            viewDesc.setVisibility(View.GONE);
            viewDesc2.setVisibility(View.GONE);
            descriptionTitle.setVisibility(View.GONE);
            tvDescription.setVisibility(View.GONE);
        } else {
            viewDesc.setVisibility(View.VISIBLE);       
            descriptionTitle.setVisibility(View.VISIBLE);
            tvDescription.setVisibility(View.VISIBLE);
            tvDescription.setText(description[0]);
            viewDesc2.setVisibility(View.VISIBLE);
        }


                }                                   

    protected void onPreExecute(){      


        dialog = ProgressDialog.show(Radio.this, "", 
                    "Loading. Please wait...", true);                                   
    }
}

2 个答案:

答案 0 :(得分:2)

即使可以,也不想让AsyncTask静态。每个实例都适合一次拍摄,永远不能再次运行。

ActivityService之间似乎有一些沟通。在这种情况下,你应该研究binding the service to your activity。您可以轻松地来回调用方法,也可以设置MessageHandler频道,如果您想要异步执行。

答案 1 :(得分:1)

您可以轻松地将其声明为静态。

您只需要传递对Activity的引用,以便访问其成员。

通过使其成为静态,您将失去对外部类实例成员的访问权限,因此只需通过将其传递给AsyncTask的构造函数,然后在访问它之前将其检查为null来维护对活动的引用。

我还建议将其设为WeakReference

  • 可辩论的好处是AsyncTask不会持有引用 回到它的父Activity(java中的内部类得到一个强大的ref 回到父母,除非他们是静止的)。

  • 这将允许在用户使用时进行GC(垃圾收集)活动 切换屏幕。

  • 否则它将保持活动状态,直到AsyncTask完成并释放引用。

这是一个代码示例

private static class StatusLoader extends AsyncTask <Boolean, Void, ServiceStatus> {
    WeakReference<StatusActivity> _act;
    StatusLoader(StatusActivity pActivity) {
        _act = new WeakReference<StatusActivity>(pActivity);
    }

    @Override
    protected ServiceStatus doInBackground(Boolean... params) {
        ServiceStatus retval = null;
        boolean bUseCache = params[0];
        retval = StatusMgr.getStatus(bUseCache); // do work...
        return retval;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        StatusActivity act = _act.get();
        if (act != null) {
            act._mData.showProgress(U.getStringRes(R.string.progress_msg_status_update));
        }
    }
    @Override
    protected void onPostExecute(ServiceStatus pResult) {
        super.onPostExecute(pResult);
        StatusActivity act = _act.get();
        if (act != null) {  // <-- in case activty is no longer alive
            act._dsStatus = pResult;
            act._mData.hideProgress();
            act._mData.bindStatusData(StatusMgr.getResultMode());
        }
    }
}