2014-02-25 27 views
0

因此,我正在編寫一個應用程序,它從我創建的CSVDownloader類中下載CSVFile。Android每週文件下載或startIntent功能

現在我的應用程序正在等待文件下載並等待SplashActivity,然後繼續。這可能是漫長和厭倦每次加載應用程序,所以我想要做的事情基本上是比較時間戳日期與日期值在一週的時間(即+7),只有下載文件,如果原始文件是一週舊。

有人可以看看我的代碼,並建議修改,使這種似是而非?

SplashActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_splash); 
    bar = (ProgressBar) findViewById(R.id.progress_bar); 

    Thread thread = new CSVDownloader(this); 
    thread.start(); 

    handler.post(new Runnable() { 
     public void run() { 
      Intent intent = new Intent(SplashActivity.this, MapActivity.class); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
    //make spinner and make run 
} 

而且CSVDownloader線程任務:

package uk.ac.aber.dwd.util.CeredigionTourism; 

import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Date; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import uk.ac.aber.dwd.CeredigionTourism.SplashActivity; 

import android.database.sqlite.SQLiteDatabase; 
import android.os.Environment; 
import android.text.format.DateFormat; 

/** 
* CSVDownloader extends Thread and will download CSV records and turn them into Map/List markers. 
* @author danieldrave 
* 
*/ 
public final class CSVDownloader extends Thread { 

private SplashActivity splashActivity; 

/** 
* @param splashActivity 
*/ 
public CSVDownloader(SplashActivity splashActivity) { 
    this.splashActivity = splashActivity; 
} 

@Override 
public void run() { 

    String filePath = downloadCSVFile(); 
    BufferedReader buffer; 

    if(filePath == null){ 
     System.err.println("File Path was null"); 
     return; 
    } 

    MySQLiteHelper db = new MySQLiteHelper(splashActivity); 

    try { 
     buffer = new BufferedReader(new FileReader(new File(filePath))); 
     String line = buffer.readLine(); //read first line because its headers and discard 
     String relLine; 

     while ((relLine = buffer.readLine()) != null) { 
      while(relLine.contains("\t\t")) 
       relLine = relLine.replace("\t\t","\t \t"); //REPLACE FUNCTION FOR SPACE BETWEEN TABS 
      String[] str = relLine.split("\t"); 
      if(str.length < 9){ 
       System.err.println("My client got it wrong"); 
       System.err.println(str); 
       continue; 
      } 

      MapMarker marker = new MapMarker(); 
      marker.setGroup(str[0]); 
      marker.setName(str[1]); 
      marker.setImage(str[2]); 
      marker.setDescription(str[3]); 
      marker.setAddress(str[4]); 
      marker.setTelephone(str[5]); 
      marker.setUrl(str[6]); 
      marker.setLatitude(str[7]); 
      marker.setLongitude(str[8]); 

      db.addMapMarker(marker); //ADD COMPLETED MAP MARKER WITH INDEXED COLUMN VALUES 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    System.out.println("FILE DOWNLOADED: " + filePath); 
} 

private String downloadCSVFile() { 

    final String filename = "locations.csv"; 
    String filePath = null; 
    BufferedOutputStream bos; 

try { 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    httpClient.getCredentialsProvider().setCredentials(
     new AuthScope(null, -1), 
     new UsernamePasswordCredentials("username", "password")); 

    HttpGet httpGet = new HttpGet("http://www.cardigan.cc/app/locations.csv"); 

     //GET FILE FROM URL AND WRITE TO LOCATIONS.CSV LOCALLY 
     HttpResponse response = httpClient.execute(httpGet); 
     HttpEntity entity = response.getEntity(); 
     if(entity != null){ 
      BufferedInputStream bis = new BufferedInputStream(entity.getContent()); 
      filePath = Environment.getExternalStorageDirectory().toString() + "/" +filename; 
      bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); 
      int inByte; 
      while((inByte = bis.read()) != -1) bos.write(inByte); 
      bis.close(); 
      bos.close(); 
     } 

     else if(entity == null) { 
      System.out.println("NO FILE DOWNLOADED FROM SERVER"); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return filePath;     
} 
} 

任何幫助,任何人都可以提供將是了不起的,謝謝。

+0

能ÿ ou保存上次下載的文件並使用該日期,或者您需要檢查文件是否比1周更早?你可以添加文件在標題響應上創建的時間嗎? – GhostDerfel

+0

@GhostDerfel它將完全使用該文件的下載日期。然後我想將它與一週內的日期進行比較。所以我假設'dateDownloaded <= dateDownloaded + 7'圍繞該邏輯:) – user3319818

回答

0

也許您可以使用file.lastModified()方法獲取設備上最後修改日期locations.csv並比較日期。如果超過一個星期的時間,運行方法。

一些代碼從我的頭:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), your_file_name); 

Date lastModified = new Date(file.lastModified()); 

//... use lastModified to check date 

希望幫助

0

你應該看看SharedPreferences和這個Date對象。

這將完成你的工作,並調整你的飛濺,直到1.5秒後才能完成。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_splash); 
    bar = (ProgressBar) findViewById(R.id.progress_bar); 

    if(shouldUpdateCSV()){ 
     Thread thread = new CSVDownloader(this); 
     thread.start(); 
     updateLastCheckedDate(context); // Call this after you've completed your CSVDownload, not just after starting the Thread to make sure it actually does update. 
    } 

    handler.postDelayed(new Runnable() { 
     public void run() { 
      Intent intent = new Intent(SplashActivity.this, MapActivity.class); 
      startActivity(intent); 
      finish(); 
     } 
    }, 1500); // Use postDelayed to have it post to the main thread after x milliseconds 
} 

public boolean shouldUpdateCSV(){ 
    return new Date().getTime() - getLastCheckedDate() > 1000 * 60 * 60 * 24 * 7; 
} 

public long getLastCheckedDate(){ 
    return getSharedPreferences("preference_name", 0).getLong("pref_last_checked_timestamp", 0); 
} 

public static void updateLastCheckedDate(Context context){ 
    context.getSharedPreferences("preference_name", 0).edit().putLong("pref_last_checked_timestamp", new Date().getTime()).commit(); 
} 
0

首先,你需要存儲下載的資料,您完成文件下載後添加類似的東西:

SharedPreferences sp = context.getSharedPreferences("filedetails", MODE_PRIVATE); 
Editor editor = sp.edit(); 
shared.putLong(MY_STATIC_STRING_TO_REFERENCE,System.currentTimeInMillis()); 
editor.commit(); 

然後你開始下載前,您可以檢查日期這樣的:

SharedPreferences sp= context.getSharedPreferences("filedetails", MODE_PRIVATE); 
long lastDownload= userDetails.getString(MY_STATIC_STRING_TO_REFERENCE, null); 
long today = System.currentTimeInMillis(); 
if((lastDownload+1000*60*60*24*7)<today){ 
    //Do download 
} 

所有的代碼被直接完成對堆棧溢出,從而可以包含一些錯誤,對不起;(