Android每周文件下载或startIntent功能

时间:2014-02-25 01:52:23

标签: java android xml sqlite

所以我正在编写一个从我创建的CSVDownloader类下载CSV文件的应用程序。

现在我的应用程序只是等待文件下载并等待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;                
}
}

任何人都能提供的任何帮助都会非常棒,谢谢。

3 个答案:

答案 0 :(得分:0)

也许您可以使用file.lastModified()方法获取设备上locations.csv的上次修改日期并比较日期。如果它超过一周的时间,请运行downloadCSV()方法。

我脑子里有些代码:

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

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

//... use lastModified to check date

希望有所帮助

答案 1 :(得分:0)

您应该查看SharedPreferencesDate对象。

这将为您完成工作,并在1.5秒之后将Splash调整为不完成。

@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(); 
}

答案 2 :(得分: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
}

所有代码都直接在Stack Overflow上完成,因此可能包含一些错误,抱歉;(