Android WebView 不存储 cookie 或删除它们

Android WebView doesn't store cookies or deletes them

所以,我开始开发一款使用 ONE webview 的应用程序。该应用程序有一个登录按钮,如果您按下该按钮,则会将您定向到名为 csgolounge.com 的网站的 Steam 登录页面。我还实现了一个导航抽屉,你应该能够通过该网站的不同菜单进行导航。五小时前,我遇到了这个问题,当我登录 Steam 并通过导航抽屉切换到该网站的另一个菜单时(例如从 www.csgolounge.com 到 www.csgolounge.com/myprofile) ,我没有登录了。当我转动移动设备时,会话也会发生变化!直到现在,我还是想不通,Whosebug 上也没有适合我的解决方案!

我想我的问题与 cookie 有关,所以请帮助我:(

这是 MainActivity:

public class HomeActivity extends Activity {

ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public static WebView webview;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[9];

    drawerItem[0] = new ObjectDrawerItem(0, "My Profile");
    drawerItem[1] = new ObjectDrawerItem(0, "My Trades");
    drawerItem[2] = new ObjectDrawerItem(0, "My Offers");
    drawerItem[3] = new ObjectDrawerItem(0, "My Bets");
    drawerItem[4] = new ObjectDrawerItem(0, "Bookmarks");
    drawerItem[5] = new ObjectDrawerItem(0, "Search");
    drawerItem[6] = new ObjectDrawerItem(0, "Add Trade");
    drawerItem[7] = new ObjectDrawerItem(0, "Reddit");
    drawerItem[8] = new ObjectDrawerItem(0, "Rules");

    DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
    mDrawerList.setAdapter(adapter);
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(
            this,
            mDrawerLayout,
            R.drawable.ic_launcher,
            R.string.drawer_open,
            R.string.drawer_close
    ) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
        }
        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /** Buttons */
    final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.openDrawer(mDrawerList);
            } else {
                mDrawerLayout.closeDrawer(mDrawerList);
            }
        }
    });

    webview = (WebView) findViewById(R.id.webView);
    webview.setWebViewClient(new mWebViewClient());

    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setSavePassword(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("https://steamcommunity.com/openid/login?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=checkid_setup&openid.return_to=https%3A%2F%2Fcsgolounge.com%2Flogin&openid.realm=https%3A%2F%2Fcsgolounge.com&openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

public static boolean itemSelected = false;
public static int itemSelectedNumber;

private void selectItem(int position) {
    mDrawerList.setItemChecked(position, true);
    mDrawerList.setSelection(position);
    switch (position) {
        case 0:
            webview.loadUrl("http://www.csgolounge.com/myprofile");
            itemSelectedNumber = 0;
            break;
        case 1:
            webview.loadUrl("http://www.csgolounge.com/mytrades");
            itemSelectedNumber = 1;
            break;
        case 2:
            webview.loadUrl("http://www.csgolounge.com/myoffers");
            itemSelectedNumber = 2;
            break;
        case 3:
            webview.loadUrl("http://www.csgolounge.com");
            itemSelectedNumber = 3;
            break;
        case 4:
            webview.loadUrl("http://www.csgolounge.com/bookmarks");
            itemSelectedNumber = 4;
            break;
        case 5:
            webview.loadUrl("http://www.csgolounge.com/search");
            itemSelectedNumber = 5;
            break;
        case 6:
            webview.loadUrl("http://www.csgolounge.com/addtrade");
            itemSelectedNumber = 6;
            break;
        case 7:
            webview.loadUrl("http://www.reddit.com/r/csgolounge");
            itemSelectedNumber = 7;
            break;
        case 8:
            webview.loadUrl("http://www.csgolounge.com/rules");
            itemSelectedNumber = 8;
            break;

        default:
            break;
    }
    itemSelected = true;
    mDrawerLayout.closeDrawer(mDrawerList);
}

}

我的 LoginActivity,它只有一个按钮,当您单击它时,会启动 HomeActivity:

public class LoginActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    final Button button = (Button) findViewById(R.id.btn_SignIn);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent logIn = new Intent(LoginActivity.this, HomeActivity.class);
            startActivity(logIn);
        }
    });
}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

我的 WebViewClient(mViewClient) 只是覆盖了一些函数,以便能够在加载时阻止来自 csgolounge.com 网站的不同元素:

public class mWebViewClient extends WebViewClient {

public mWebViewClient() {
}

public boolean shouldOverrideUrlLoading(WebView webview, String s) {
    webview.loadUrl(s);
    return true;
}

public void onPageFinished(WebView view, String url){
    super.onPageFinished(view, url);
}

public void onLoadResource(WebView view, String url) {
    super.onLoadResource(view, url);
    if (HomeActivity.itemSelected == false && url.contains("csgolounge.com") && !url.contains("steamcommunity.com")) {
        view.loadUrl("javascript:(function() { " +
                "document.getElementsByTagName('section')[1].style.display = 'none'; " +
                //"document.getElementsByTagName('header')[0].style.display = 'none'; " +
                "document.getElementsByTagName('div')[4].style.display = 'none'; " +
                "document.getElementsByTagName('aside')[0].style.display = 'none';" +
                "})()");
    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 0) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 1) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 2) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 3) {
        view.loadUrl("javascript:(function() { " +
                "document.getElementsByTagName('section')[0].style.display = 'none'; " +
                "document.getElementsByTagName('header')[0].style.display = 'none'; " +
                "document.getElementsByTagName('div')[4].style.display = 'none'; " +
                "document.getElementsByTagName('aside')[0].style.display = 'none';" +
                "})()");
    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 4) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 5) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 6) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 7) {

    }
    else if (HomeActivity.itemSelected == true && HomeActivity.itemSelectedNumber == 8) {

    }
}

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    //Users will be notified in case there's an error (i.e. no internet connection)
    Toast.makeText(view.getContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}

}

ObjectDrawerItem Class:

public class ObjectDrawerItem {

public int icon;
public String name;

// Constructor.
public ObjectDrawerItem(int icon, String name) {

    this.icon = icon;
    this.name = name;
}

}

DrawerItemCustomAdapter Class:

public class DrawerItemCustomAdapter extends ArrayAdapter<ObjectDrawerItem> {

Context mContext;
int layoutResourceId;
ObjectDrawerItem data[] = null;

public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, ObjectDrawerItem[] data) {

    super(mContext, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View listItem = convertView;

    LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
    listItem = inflater.inflate(layoutResourceId, parent, false);

    ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);
    TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);

    ObjectDrawerItem folder = data[position];


    imageViewIcon.setImageResource(folder.icon);
    textViewName.setText(folder.name);

    return listItem;
}

}

主页活动设计:http://prntscr.com/62balt http://prntscr.com/62bb7u 和文字:

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:longClickable="false"
android:background="#FF535353">
<!-- The main content view -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_frame"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity"
    android:weightSum="1">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="48dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="MYCSGOLOUNGE"
            android:id="@+id/text_Header"
            android:gravity="center"
            android:background="#ffff9836"
            android:editable="false"
            android:typeface="sans"
            android:layout_gravity="center_horizontal"
            android:textSize="24dp"
            android:visibility="visible"
            android:textColor="#ffffffff"
            android:textIsSelectable="false" />

        <ImageButton
            android:layout_width="48dp"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton"
            android:layout_alignBottom="@+id/text_Header"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:src="@drawable/ic_menu" />

        <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_alignParentBottom="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/text_Header" />
    </RelativeLayout>

</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#ffff9836"/>

片段的东西让我失望了,但看起来是因为 URL 以 www 开头所以它认为它是一个不同的域。将其更改为 webview.loadUrl("http://csgolounge.com/myprofile"); 解决了我的问题。