Android WebView在Back上按两次崩溃

时间:2016-05-08 11:39:50

标签: android webview

我有一个WebView,当视图可以返回时双击后退按钮会崩溃。会发生什么,是在第一次Back按下时,它会导致页面返回(导致上一页的加载(页面A)。然后第二个onKeyDown事件到来并杀死WebView(如预期的那样)。问题是在WebView被杀之后,页面A继续加载(由于第一次按下Back按钮),并且调用了onPageStarted和onPageFinished。这些函数使应用程序崩溃,因为webView已经被破坏。我该怎么办?

use std::boxed::Box;
use std::collections::HashMap;
use std::fmt;

pub type TileMap = HashMap<(i32, i32), Box<Tile>>;

pub trait Tile: fmt::Debug {
    fn new(x: i32, y: i32) -> Self where Self: Sized;
    fn update_into(&self, app: &App, new_tiles: &mut TileMap);
}

#[derive(Copy, Clone, Debug)]
pub struct DirtTile {
    pub x: i32,
    pub y: i32
}

impl Tile for DirtTile {
    fn new(x: i32, y: i32) -> DirtTile {
        return DirtTile { x: x, y: y };
    }

    fn update_into(&self, app: &App, new_tiles: &mut TileMap) {
        let world = &app.world;

        let new_pos = (self.x + 1, self.y);
        if world.tiles.get(&new_pos).is_none() {
            new_tiles.insert(new_pos, Box::new(DirtTile::new(self.x + 1, self.y)));
        }
        else {
            new_tiles.insert((self.x, self.y), Box::new(*self));
        }
    }
}

pub struct World {
    tiles: TileMap,
}

pub struct App {
    world: World,
}

fn main() {
    let mut app = App { world: World { tiles: HashMap::new() } };

    app.world.tiles.insert((0, 0), Box::new(DirtTile::new(0, 0)));

    let mut new_tiles = HashMap::new();
    for (_, tile) in &app.world.tiles {
        tile.update_into(&app, &mut new_tiles);
    }
    app.world.tiles = new_tiles;

    println!("{:?}", app.world.tiles);
}

2 个答案:

答案 0 :(得分:0)

 @Override
public boolean onKeyDown(int keycode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keycode) {
            case KeyEvent.KEYCODE_BACK:
                if (view.canGoBack()) {
                    view.goBack();
                } else {
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keycode, event);
}
}

这在我的情况下工作添加'return true;'在案例中的陈述......

答案 1 :(得分:0)

@Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        try{

            //your code here

        }
        catch (Exception e){

        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        try{

            //your code here
        }
        catch (Exception e){

        }
    }

这对我有用。使用try catch in onPageStarted()和onPageFinished()。 我认为这也对您有效,请尝试一下。

相关问题