从Service更新活动TextView

时间:2012-10-26 10:25:04

标签: android service android-intent

我需要下载100MB的图片,因此我认为最好的方法是让服务下载它,并在活动中显示每个文件的结果。但这就像没有服务,活动fzreees,并且只在下载所有文件后解冻。

以下是活动代码:

public class DownloadActivity extends Activity 
{
String hist;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.download_activity);

    startService(new Intent(this, DownloadService.class));
    registerReceiver(broadcastReceiver, 
            new IntentFilter(DownloadService.BROADCAST_ACTION));
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() 
{
    @Override
    public void onReceive(Context context, Intent _intent) 
    {
        updateUI(_intent);       
    }
};

private void updateUI(Intent intent) 
{
    if (intent.getBooleanExtra("exists", false))
        hist = hist + "Item " + 
                intent.getIntExtra("item", -1) + ", image " + 
                intent.getIntExtra("obraz", -1) + " - DOWNLOADED\n";
    else
        hist = hist + "Item " + 
                intent.getIntExtra("item", -1) + ", image " + 
                intent.getIntExtra("obraz", -1) + " - ALREADY EXISTS\n";

    ((TextView) findViewById(R.id.dtitle)).setText("Item " + 
            intent.getIntExtra("item", -1) + ", image " + 
                    intent.getIntExtra("image", -1) + ".");

    ((TextView) findViewById(R.id.ddetails)).setText(hist);
}
}

服务代码:

public class DownloadService extends Service
{
public static final String BROADCAST_ACTION = "emis.katalog.grzybow.publishprogress";
Intent intent;
int counter = 0;
String postString;

@Override
public IBinder onBind(Intent arg0) 
{
    // TODO Auto-generated method stub
    return null;
} 
@Override
public void onCreate() 
{
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);  
}

@Override
public void onStart(Intent intent, int startId) 
{ 
    SQLiteDatabase db = new BazaGrzybowHelper(DownloadService.this).getReadableDatabase();
    Cursor kursor = db.rawQuery("SELECT * FROM table", null);

    InputStream in = null;
    OutputStream out = null;
    URL ulrn;

    int nn = 1;
    int pos = 1;

    //out:
        while(kursor.moveToNext())
        {
            while(kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != "" || 
                    kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != null)
            {
                String filename = "thg_" + pos + "_" + (nn+2) + ".jpg";
                if (new File(Environment.getExternalStorageDirectory(),
                        "emis/katalog.grzybow/zapis_na_stale/"+filename).exists())
                    publishProgress(pos, nn, true);
                else
                {
                    publishProgress(pos, nn, false);


                    File destDir = new File(Environment.getExternalStorageDirectory(),
                            "emis/katalog.grzybow/zapis_na_stale");
                    if (!destDir.exists())
                        destDir.mkdirs();
                    destDir = null;

                    try 
                    {
                        ulrn = new URL(kursor.getString(kursor.getColumnIndex("i_url_" + nn)));
                        HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
                        in = con.getInputStream();
                        out = new FileOutputStream(Environment.getExternalStorageDirectory().
                                getPath() + "/emis/katalog.grzybow/zapis_na_stale/" + filename);
                        copyFile(in, out);
                        in.close();
                        in = null;
                        out.flush();
                        out.close();
                        out = null;
                    } 
                    catch(Exception e) 
                    {
                        e.printStackTrace();
                    }
                }
                nn++;

                if (nn > 10 || kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == "" || 
                        kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == null)
                {
                    nn = 1;
                    break;
                }
                /*if (anuluj)
                    break out;*/
            }
            pos++;
        }

    db.close();
}

private void publishProgress(int item, int image, boolean exists) 
{
    intent.putExtra("item", item);
    intent.putExtra("image", image);
    intent.putExtra("exists", exists);
    sendBroadcast(intent);
}

private void copyFile(InputStream in, OutputStream out) throws IOException 
{
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1)
    {
        out.write(buffer, 0, read);
    }
}

}

我做错了什么?

1 个答案:

答案 0 :(得分:3)

也许是this

  

警告:服务在其托管进程的主线程中运行 -   service不会创建自己的线程,也不会单独运行   过程(除非您另行指定)。这意味着,如果你的   服务将进行任何CPU密集型工作或阻塞操作   (如MP3播放或网络),你应该创建一个新的线程   在服务范围内做这项工作。通过使用单独的线程,你   将降低应用程序无响应(ANR)错误的风险   应用程序的主线程可以保持专用于用户交互   与您的活动。