活动有时不会在android中重启

时间:2013-12-02 04:52:03

标签: android android-activity

以下代码下载了一些文件(视频和图像)。下载文件后,将重新启动活动以完成重新加载过程。问题是,即使正确显示消息,活动有时也不会重新启动。这似乎发生在播放视频时。

public class FastFTPDownloader extends DownloaderBase {

    public FastFTPDownloader(Activity activity, Intent intent) {
        super(activity, intent);
    }

    @Override
    protected String doInBackground(String... params) {
        FastFTPDownloader.setDoing(true);
        FTPClient client = new FTPClient();
        FTPFile[] files = null;
        client.setType(FTPClient.TYPE_BINARY);
        try {
            client.connect(params[0]);
            client.login(params[1], params[2]);
            client.changeDirectory(params[3]);
            File alphalist = new File(ConfigLoader.ALPHA_PATH + "list.txt");
            File betalist = new File(ConfigLoader.BETA_PATH + "list.txt");

            // Step 1: download list.txt to alpha folder
            client.download("list.txt", alphalist);
            Log.d("Pankaj " + this.getClass().toString(),
                    "Downloading list.txt");

            // Step 2: compare list.txt in alpha with list.txt in beta
            // if both are same size return and do nothing
            if (betalist.length() == alphalist.length()) {
                // FastFTPDownloader.setDoing(false);
                Log.d("Pankaj " + this.getClass().toString(),
                        "Nothing to download");
                return "Nothing to download";
            }
            // Step 3: get a list of files from the server
            files = client.list();
            // for each file in list if file exists move on to next file
            for (FTPFile f : files) {
                File betafile = new File(ConfigLoader.BETA_PATH + f.getName());
                if (betafile.exists()) {
                    if (betafile.length() == f.getSize()) {
                        continue;
                    }
                }
                // Step 4: the file does not exist in beta so download to alpha
                // if it is not there
                File alphaFile = new File(ConfigLoader.ALPHA_PATH + f.getName());
                if (alphaFile.exists()) {
                    // if files are same size move on to next file.
                    if (alphaFile.length() == f.getSize()) {
                        continue;
                    }
                    // if existing file is less than the remote file continue
                    // download
                    // for files having size > remote file do a complete
                    // download.
                    if (alphaFile.length() < f.getSize()) {
                        client.download(f.getName(), alphaFile,
                                alphaFile.length());
                        continue;
                    }
                }
                client.download(f.getName(), alphaFile);
            }
        } catch (IllegalStateException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (IOException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (FTPIllegalReplyException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (FTPException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (FTPDataTransferException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (FTPAbortedException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (FTPListParseException e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        } catch (Exception e) {
            Log.e(getClass().getName(), e.getMessage());
            // FastFTPDownloader.setDoing(false);
            return e.getMessage();
        }
        File alpha = new File(ConfigLoader.ALPHA_PATH);
        File beta = new File(ConfigLoader.BETA_PATH);

        File[] betaFiles = beta.listFiles();

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(activity, "Restarting Please Wait...",
                        Toast.LENGTH_LONG).show();
            }
        });
        // Step 5: shutdown the activity to complete the reconfiguration
        VideoView video = ConfigLoader.getVideo();
        if (video.isPlaying()) {
            video.stopPlayback();
        }
        activity.overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        activity.finish();
        // ConfigLoader.getResources().reload();
        // Step 6: if the file is not in list then delete it from beta
        for (File f : betaFiles) {
            if (!existsInList(f.getName())) {
                f.delete();
            }
        }
        File[] alphaFiles = alpha.listFiles();
        // Step 7: move the remaining files in alpha to beta.
        for (File f : alphaFiles) {
            moveToBeta(f);
        }

        // Step 8: restart the application with new configurations.
        activity.overridePendingTransition(0, 0);
        activity.startActivity(intent);
        return "Activity Restarted Successfully";
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
        FastFTPDownloader.setDoing(false);
        super.onPostExecute(result);
    }

    private void moveToBeta(File file) {
        File betaFile = new File(ConfigLoader.BETA_PATH + file.getName());
        try {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(betaFile);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            file.delete();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

下载程序库代码: -

public abstract class DownloaderBase extends AsyncTask<String, Integer, String> {

    protected Activity activity;
    protected Intent intent;
    private static boolean doing = false;

    public static boolean isDoing() {
        return doing;
    }

    public static void setDoing(boolean doing) {
        DownloaderBase.doing = doing;
    }

    public DownloaderBase(Activity activity, Intent intent) {
        this.activity = activity;
        this.intent = intent;
    }

    protected void deleteSubFolders(String uri) {
        File currentFolder = new File(uri);
        File files[] = currentFolder.listFiles();

        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                deleteSubFolders(f.toString());
            }
            // no else, or you'll never get rid of this folder!
            f.delete();
        }
    }

    protected void copyFromBeta() throws IOException {
        File beta = new File(ConfigLoader.BETA_PATH);
        File alpha = new File(ConfigLoader.ALPHA_PATH);
        File[] files = beta.listFiles();
        for (File f : files) {
            String fname = f.getName().toLowerCase();
            if (!fname.endsWith(".mp4")) {
                continue;
            }
            if (!existsInList(f.getName())) {
                continue;
            }
            FileInputStream fis = new FileInputStream(f);
            File copy = new File(alpha + f.getName());
            FileOutputStream fos = new FileOutputStream(copy);
            byte[] buf = new byte[1024];
            int len;
            while ((len = fis.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
            fis.close();
            fos.close();
        }
    }

    protected void trimAlpha() {
        File alpha = new File(ConfigLoader.ALPHA_PATH);
        File[] files = alpha.listFiles();
        for (File f : files) {
            if (!existsInList(f.getName())) {
                f.delete();
            }
        }
    }

    protected boolean existsInList(String filename) {
        File list = new File(ConfigLoader.ALPHA_PATH + "list.txt");
        try {
            FileReader fr = new FileReader(list);
            BufferedReader br = new BufferedReader(fr);
            String s;
            while ((s = br.readLine()) != null) {
                if (s.equals(filename)) {
                    return true;
                }
            }
            br.close();
        } catch (FileNotFoundException e) {
            Log.e(getClass().getName(), e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

}

主要活动代码: -

public class MainActivity extends Activity implements Runnable {
    private Handler h;
    private MediaPlayer player;
    private Standee standee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        ImageView iv = (ImageView) findViewById(R.id.imageView1);
        VideoView vv = (VideoView) findViewById(R.id.videoView1);

        standee = new Standee(this, vv, iv);
        standee.start();

        h = new Handler();
        h.post(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void run() {
        if (!FastFTPDownloader.isDoing()) {
            h.removeCallbacks(this);
            FastFTPDownloader ftp = new FastFTPDownloader(this, getIntent());
            ConfigLoader l = ConfigLoader.getInstance();
            ftp.execute(l.URL(), l.User(), l.Password(), l.Path());
            h.postDelayed(this, l.Delay() * 1000);
        }
    }

    @Override
    protected void onDestroy() {
        player = standee.getMediaPlayer();
        player.stop();
        player.release();
        player = null;
        super.onDestroy();
    }

}

感谢任何帮助。提前致谢。如果需要,我正在使用FTP4j库。

1 个答案:

答案 0 :(得分:0)

最可能的原因是Android正在销毁和重新创建活动。因此,AsyncTask对活动的引用将变为无效。有一种模式可以解决这个问题。

  1. 在AsyncTask中,提供“附加”方法:

    public void attach(活动活动){     this.activity =活动; }

  2. 在您的活动类中,总是将当前版本的活动与任务挂钩,如下所示:

    static AsyncTask myTask = ....

  3. 和onCreate()或onResume()

    if (myTask != null) myTask.attach(this);