代码

来源:互联网 发布:淘宝欧斯曼真皮双肩包 编辑:程序博客网 时间:2024/05/29 09:37
package com.bbk.appstore.ui;import java.util.HashMap;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.LocalActivityManager;import android.app.TabActivity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.content.SharedPreferences;import android.content.SharedPreferences.OnSharedPreferenceChangeListener;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.content.res.Resources;import android.content.res.TypedArray;import android.graphics.Color;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.Uri;import android.os.AsyncTask;import android.os.Build;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.telephony.TelephonyManager;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.inputmethod.InputMethodManager;import android.widget.Button;import android.widget.CheckBox;import android.widget.ImageView;import android.widget.TabHost;import android.widget.TabWidget;import android.widget.TextView;import android.widget.TabHost.TabSpec;import com.bbk.appstore.AppstoreApplication;import com.bbk.appstore.R;import com.bbk.appstore.download.AutoUpdateReceiver;import com.bbk.appstore.download.AutoUpdateService;import com.bbk.appstore.download.Management;import com.bbk.appstore.download.OpenDownloadReceiver;import com.bbk.appstore.download.OpenDownloadService;import com.bbk.appstore.model.DataLoader;import com.bbk.appstore.net.HttpConnect;import com.bbk.appstore.net.HttpResponed;import com.bbk.appstore.net.NetworkUtilities;public class AppStore extends TabActivity implements ClickableTabHost.OnTabSelectedListener{private static final String TAG = "AppStore";private ChangeTabReceiver mReceiver = null;private static final String INTENT_ACTION_NETWORK_SETTINGS = "android.settings.NETWORK_SETTINGS";private static final String INTENT_ACTION_WIFI_SETTINGS = "android.settings.WIFI_SETTINGS";public static final String CHANGE_TAB_ACTION = "com.bbk.appstore.ACTION_CHANGE_TAG";public static final String EXTRA_TARGET_TAB_KEY = "com.bbk.appstore.TARGET_TAB";public static final String MANAGEMENT_TARGET_TAB_KEY = "com.bbk.appstore.MANAGEMENT_TARGET_TAB";public static final String ACTION_VIEW_HUB = "com.bbk.appstore.ACTION_VIEW_HUB_COMPLEX";public static final String ACTION_SEARCH = "com.bbk.appstore.Action.SEARCH_PACKAGE";private static final int DLG_NO_CONNECTION = 0;private static final int DLG_NO_WIFI = 1;private static final int MSG_VERSION_SUCCESS = 0;private static final int MSG_VERSION_FAILED = 1;private boolean mAppstoreStarted = false;private InputMethodManager mInputMethodManager;private SharedPreferences mUpdatePrefs = null;private UpdateChangedListener mUpdateChangedListener = null;private TextView mUpdateNumText = null;    private int mFontSizeDefault;    private int mFontSizeSmall;        private Bundle mExtraData = null;      private Uri parameUri = null;    private String hostStr = null;    private String schemeStr = null;    private LayoutInflater mInflater = null;    private static HashMap<String, String> keyHashMap = new HashMap<String, String>();        private String key = null;        private TabWidget mTabwidget;  private static Class<?> TAB_ACTIVITY_CLASSES[] = {RecommendedListActivity.class,CategoriyListActivity.class,TopPackageListActivity.class,Search.class,Management.class};//AccountUtils mAccount = null;private NetworkReceiver mNetworkChanedReceiver = null;private boolean mNewInstance = false;private boolean mPaused = true;private boolean mWifiChanged = false;private boolean noNetwork = false;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);this.getWindow().setBackgroundDrawableResource(android.R.color.transparent);mInflater = LayoutInflater.from(this);setContentView(R.layout.appstore);Resources res = getResources();        mFontSizeDefault = res.getDimensionPixelSize(R.dimen.app_notification_fontsize_default);        mFontSizeSmall = res.getDimensionPixelSize(R.dimen.app_notification_fontsize_small);//        httpConnect = new HttpConnect(this, null, null);    mNetworkChanedReceiver = new NetworkReceiver();    IntentFilter filter = new IntentFilter();    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);    registerReceiver(mNetworkChanedReceiver, filter);        mNewInstance = true;    }public void finish() {super.finish();AppstoreApplication.getInstance().setCache();}@Overrideprotected void onResume(){super.onResume();mPaused = false;Intent intent = getIntent();Log.i(TAG, "onResume,intent.getAction = " + intent.getAction());int type = NetworkUtilities.getConnectionType(this);if (mNewInstance || !mAppstoreStarted || mWifiChanged){mNewInstance = false;switch (type) {case NetworkUtilities.CONNECTION_TYPE_NULL:safeDismissDialog(DLG_NO_WIFI);showDialog(DLG_NO_CONNECTION);break;case NetworkUtilities.CONNECTION_TYPE_MOBILE:SharedPreferences prefs = AppstoreSettings.getSharedPreferences(this);int useMobile = prefs.getInt(AppstoreSettings.KEY_USE_MOBILE, 0);if (0 == useMobile) {safeDismissDialog(DLG_NO_CONNECTION);boolean can = prefs.getBoolean(AppstoreSettings.KEY_SAVE_FLOW_SETTING, false);mWifiChanged = false;if (can) {AppstoreSettings.mFlow = true;startAppStore();}else {showDialog(DLG_NO_WIFI, null);}} else {startAppStore();}break;case NetworkUtilities.CONNECTION_TYPE_WIFI:startAppStore();break;default:}}}@Overrideprotected void onPause(){super.onPause();mPaused = true;keyHashMap.clear();}private void startAppStore(){if(mAppstoreStarted){return;}mAppstoreStarted = true;PackageManager pm = getPackageManager();PackageInfo info = null;try{info = pm.getPackageInfo("com.bbk.appstore", PackageManager.GET_ACTIVITIES);}catch (NameNotFoundException e){Log.i(TAG, "get com.bbk.appstore info from package, catch NameNotFoundException");}AppCheckTask task = new AppCheckTask(this, info.packageName, info.versionName, info.versionCode, false);TaskExcute taskExcute = new TaskExcute();taskExcute.excuteVersion(task);//mAccount = AccountUtils.getInstance(this);//mAccount.autoLogin();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(CHANGE_TAB_ACTION);mReceiver = new ChangeTabReceiver();registerReceiver(mReceiver, intentFilter);        mUpdatePrefs = getSharedPreferences(AutoUpdateService.PREFERENCES_FILE_NAME_NEW_PACKAGE, Context.MODE_PRIVATE);        mUpdateChangedListener = new UpdateChangedListener();        mUpdatePrefs.registerOnSharedPreferenceChangeListener(mUpdateChangedListener);int updateNum = mUpdatePrefs.getInt(AutoUpdateService.PREFERENCES_KEY_NEW_PACKAGE_NUM, 0);mUpdateNumText = (TextView)findViewById(R.id.update_noti_num);setUpdateNumText(mUpdateNumText, updateNum);//start the auto update serviceIntent in = new Intent(AutoUpdateReceiver.ACTION_CHECK_UPDATE);in.setClass(this, AutoUpdateReceiver.class);sendBroadcast(in);Intent mIntent = new Intent(OpenDownloadService.FORCE_STOP_PACKAGE);mIntent.setClass(this, OpenDownloadService.class);startService(mIntent);setupTabs();if (noNetwork) {Management.setTargetIndex(OpenDownloadReceiver.INSTALLED_TARGET_LABLE);getTabHost().setCurrentTabByTag(Management.class.getName());noNetwork = false;return;}Intent intent = getIntent();mExtraData = intent.getExtras();parameUri = intent.getData();if (parameUri != null) {hostStr = parameUri.getHost();schemeStr = parameUri.getScheme();}//Log.i(TAG, "intent.getAction() = "  +intent.getAction());//Log.i(TAG, "parameUri = " + parameUri);Log.i(TAG, "startAppStore ,intent.getAction() = " + intent.getAction());//Log.i(TAG, "mExtraData = " + mExtraData);if(ACTION_VIEW_HUB.equals(intent.getAction())){getTabHost().setCurrentTabByTag(CategoriyListActivity.class.getName());}else if(ACTION_SEARCH.equals(intent.getAction())){key = intent.getStringExtra("APP_NAME");keyHashMap.put("key", key);getTabHost().setCurrentTabByTag(Search.class.getName());}else if (parameUri != null && hostStr != null && schemeStr != null) {if (hostStr.equals("market.android.com") || hostStr.equals("play.google.com")) {String path = parameUri.getEncodedPath();if (path != null && path.contains("details")) {getKeyWords("package_name",parameUri);}else {getKeyWords("key",parameUri);}getTabHost().setCurrentTabByTag(Search.class.getName());    }else if (schemeStr.equals("market") || schemeStr.equals("goMarket")) {if (hostStr.equals("details")) {getKeyWords("package_name",parameUri);}else if (hostStr.equals("search")) {getKeyWords("key",parameUri);}getTabHost().setCurrentTabByTag(Search.class.getName());}}else{String targetTab = intent.getStringExtra(EXTRA_TARGET_TAB_KEY);int values = intent.getIntExtra(MANAGEMENT_TARGET_TAB_KEY, -1);if(targetTab != null && targetTab.length() != 0){Management.setTargetIndex(values);getTabHost().setCurrentTabByTag(targetTab);}}}private void setupTabs(){Resources res = getResources();String labels[] = res.getStringArray(R.array.appstore_tab_labels);TypedArray icons = res.obtainTypedArray(R.array.appstore_tab_icons);TabHost tabHost = getTabHost();mTabwidget = this.getTabWidget();((ClickableTabHost)tabHost).setOnTabSelectedListener(this);TabSpec tab = null;Intent contentIntent = null;int tabCount = TAB_ACTIVITY_CLASSES.length;for(int i = 0; i < tabCount; i++){contentIntent = new Intent();contentIntent.setClass(this, TAB_ACTIVITY_CLASSES[i]);tab = tabHost.newTabSpec(TAB_ACTIVITY_CLASSES[i].getName());tab.setIndicator(getTabItemView(i));tab.setContent(contentIntent);tabHost.addTab(tab);}}@Overrideprotected void onDestroy(){super.onDestroy();safeDismissDialog(DLG_NO_CONNECTION);safeDismissDialog(DLG_NO_WIFI);if(mUpdatePrefs != null){mUpdatePrefs.unregisterOnSharedPreferenceChangeListener(mUpdateChangedListener);}unregisterReceiver(mNetworkChanedReceiver);if(mReceiver != null){unregisterReceiver(mReceiver);}//AccountUtils.destroyInstance();}private View getTabItemView(int index){View view = mInflater.inflate(R.layout.tab_item_view, null);ImageView imageView = (ImageView)view.findViewById(R.id.imageview);TypedArray icons = getResources().obtainTypedArray(R.array.appstore_tab_icons);if (imageView != null) {imageView.setImageDrawable(icons.getDrawable(index));}String labels[] = getResources().getStringArray(R.array.appstore_tab_labels);TextView textView = (TextView)view.findViewById(R.id.textview);textView.setText(labels[index]);return view;}protected Dialog onCreateDialog(int id, Bundle args) {Dialog dialog = null;AlertDialog.Builder builder = new AlertDialog.Builder(this);if(id == DLG_NO_CONNECTION){NoConnectionDlgListener noConnectionDlgListener = new NoConnectionDlgListener();builder.setTitle(R.string.no_network_title);builder.setMessage(R.string.no_connection_info);builder.setPositiveButton(R.string.setup_connection, noConnectionDlgListener);builder.setNegativeButton(R.string.cancel, noConnectionDlgListener);builder.setOnCancelListener(noConnectionDlgListener);dialog = builder.create();dialog.setOnDismissListener(noConnectionDlgListener);dialog.show();}else if(id == DLG_NO_WIFI){NoWifiDlgListener noWifiDlgListener = new NoWifiDlgListener();builder.setTitle(R.string.use_mobile_title);builder.setMessage(R.string.no_wifi_info);builder.setPositiveButton(R.string.open, noWifiDlgListener);builder.setNegativeButton(R.string.cancel, noWifiDlgListener);builder.setOnCancelListener(noWifiDlgListener);SharedPreferences prefs = AppstoreSettings.getSharedPreferences(AppStore.this);boolean can = prefs.getBoolean(AppstoreSettings.KEY_SAVE_FLOW_SETTING, false);if(can){AppstoreSettings.mFlow = true;startAppStore();return null;}dialog = builder.create();dialog.setOnDismissListener(noWifiDlgListener);dialog.show();}return dialog;}protected void onPrepareDialog(int id, Dialog dialog, Bundle args){super.onPrepareDialog(id, dialog, args);}@Overridepublic boolean onCreateOptionsMenu(Menu menu){return MenuHelper.onCreateOptionsMenu(this, menu);}@Overridepublic boolean onPrepareOptionsMenu(Menu menu){if (mInputMethodManager == null) {mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);}mInputMethodManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);return MenuHelper.onPrepareOptionsMenu(this, menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem item){return MenuHelper.onOptionsItemSelected(this, item);}@Overridepublic void onNewIntent(Intent intent){mExtraData = intent.getExtras();parameUri = intent.getData();Log.i(TAG, "onNewIntent, intent.getAction() = " + intent.getAction());Log.i(TAG, "onNewIntent, key = " + intent.getStringExtra("APP_NAME"));if (parameUri != null) {hostStr = parameUri.getHost();schemeStr = parameUri.getScheme();}if(ACTION_VIEW_HUB.equals(intent.getAction())){getTabHost().setCurrentTabByTag(CategoriyListActivity.class.getName());}else if(ACTION_SEARCH.equals(intent.getAction())){Log.i(TAG, "ACTION_SEARCH");key = intent.getStringExtra("APP_NAME");keyHashMap.put("key", key);getTabHost().setCurrentTabByTag(Search.class.getName());}else if (parameUri != null && hostStr != null && schemeStr != null) {if (hostStr.equals("market.android.com") || hostStr.equals("play.google.com")) {String path = parameUri.getEncodedPath();if (path != null && path.contains("details")) {getKeyWords("package_name",parameUri);}else {getKeyWords("key",parameUri);}getTabHost().setCurrentTabByTag(Search.class.getName());    }else if (schemeStr.equals("market") || schemeStr.equals("goMarket")) {if (hostStr.equals("details")) {getKeyWords("package_name",parameUri);}else if (hostStr.equals("search")) {getKeyWords("key",parameUri);}getTabHost().setCurrentTabByTag(Search.class.getName());}}else{String targetTab = intent.getStringExtra(EXTRA_TARGET_TAB_KEY);int values = intent.getIntExtra(MANAGEMENT_TARGET_TAB_KEY, -1);//            Log.i(TAG, "values = " + values);if(targetTab != null && targetTab.length() != 0){Management.setTargetIndex(values);getTabHost().setCurrentTabByTag(targetTab);}}}public void onTabSelected(int index, int preIndex) {LocalActivityManager localActivityManager = getLocalActivityManager();Activity activity = localActivityManager.getActivity(TAB_ACTIVITY_CLASSES[index].getName());if(activity != null){if(activity instanceof TabActivityChild){if(index == preIndex){((TabActivityChild)activity).selectedActivity(false, mExtraData);}else{((TabActivityChild)activity).selectedActivity(true, mExtraData);}}}mExtraData = null;if (mInputMethodManager == null) {mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);}mInputMethodManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);}public boolean onSearchRequested() {return false;}private void setUpdateNumText(TextView textView, int num){Log.d(TAG, "There are " + num + " packages has new version");if(null == textView){return;}if(0 == num){textView.setVisibility(View.GONE);return;}    String numString = String.valueOf(num);    int textSize = 0;    if(num < 100){    textSize = mFontSizeDefault;    }else if(num < 1000){    textSize = mFontSizeSmall;    }else{    numString = "...";    }textView.setTextSize(textSize);textView.setText(numString);textView.setVisibility(View.VISIBLE);}private void safeDismissDialog(int dialogId){try{dismissDialog(dialogId);}catch(IllegalArgumentException e){Log.e(TAG, "safeDismissDialog, found IllegalArgumentException");}}public interface TabActivityChild{public void selectedActivity(boolean fromOtherActivity, Bundle data);}private class ChangeTabReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            if(intent.getAction().equals(CHANGE_TAB_ACTION)){                String targetTab = intent.getStringExtra(EXTRA_TARGET_TAB_KEY);                int values = intent.getIntExtra(MANAGEMENT_TARGET_TAB_KEY, -1);                Log.i(TAG, "values = " + values);                if(targetTab != null && targetTab.length() != 0){                Management.setTargetIndex(values);                    AppStore.this.getTabHost().setCurrentTabByTag(targetTab);                }            }        }}private class NoConnectionDlgListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener,DialogInterface.OnDismissListener{public void onClick(DialogInterface dialog, int which) {Intent intent = null;switch(which){case DialogInterface.BUTTON_POSITIVE:intent = new Intent(INTENT_ACTION_NETWORK_SETTINGS);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(intent);break;case DialogInterface.BUTTON_NEUTRAL:intent = new Intent(INTENT_ACTION_WIFI_SETTINGS);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(intent);break;case DialogInterface.BUTTON_NEGATIVE:safeDismissDialog(DLG_NO_CONNECTION);noNetwork = true;startAppStore();break;}}public void onCancel(DialogInterface dialog) {finish();}public void onDismiss(DialogInterface dialog) {}}private class NoWifiDlgListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener,DialogInterface.OnDismissListener{public void onClick(DialogInterface dialog, int which) {mWifiChanged = false;switch(which){case DialogInterface.BUTTON_POSITIVE:safeDismissDialog(DLG_NO_WIFI);SharedPreferences prefs = AppstoreSettings.getSharedPreferences(AppStore.this);SharedPreferences.Editor editor = prefs.edit();editor.putBoolean(AppstoreSettings.KEY_SAVE_FLOW_SETTING, true);editor.commit();AppstoreSettings.mFlow = true;startAppStore();case DialogInterface.BUTTON_NEGATIVE:safeDismissDialog(DLG_NO_WIFI);                startAppStore();break;}}public void onCancel(DialogInterface dialog) {finish();}public void onDismiss(DialogInterface dialog) {}}private class UpdateChangedListener implements OnSharedPreferenceChangeListener{public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {if(key == AutoUpdateService.PREFERENCES_KEY_NEW_PACKAGE_NUM){int updateNum = sharedPreferences.getInt(key, 0);setUpdateNumText(mUpdateNumText, updateNum);}}}private class NetworkReceiver extends BroadcastReceiver{public void onReceive(Context context, Intent intent) {        boolean mDataConnectionIsConnected = false;            NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);            NetworkInfo.State state = (networkInfo == null ? NetworkInfo.State.UNKNOWN :  networkInfo.getState());            switch (state) {            case CONNECTED:            mDataConnectionIsConnected = true;            break;            case DISCONNECTED:            if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {            mDataConnectionIsConnected = false;            } else {            mDataConnectionIsConnected = true;            }            break;            default:            }                        if(mDataConnectionIsConnected){            int type = networkInfo.getType();            if(type == ConnectivityManager.TYPE_MOBILE){            SharedPreferences prefs = AppstoreSettings.getSharedPreferences(context);int useMobile = prefs.getInt(AppstoreSettings.KEY_USE_MOBILE, 0);            if(networkInfo.isConnected()){            //now is using the mobile network            if(useMobile == 0){            safeDismissDialog(DLG_NO_CONNECTION);        if(!mPaused){        boolean can = prefs.getBoolean(AppstoreSettings.KEY_SAVE_FLOW_SETTING, false);        if (can) {        AppstoreSettings.mFlow = true;        startAppStore();        }else {        showDialog(DLG_NO_WIFI, null);        }        }else{        mWifiChanged = true;        }            }else{            safeDismissDialog(DLG_NO_CONNECTION);            safeDismissDialog(DLG_NO_WIFI);            startAppStore();            }            }else{            //the mobile network is disconnected, but the wifi is connected            }            }else if(type == ConnectivityManager.TYPE_WIFI){            if(networkInfo.isConnected()){            //now is using the wifi network        safeDismissDialog(DLG_NO_CONNECTION);        safeDismissDialog(DLG_NO_WIFI);    startAppStore();            }else{            //the wifi is disconnected, but the mobile is connected            }            }            }else{            //the network is disconnected.            if(mAppstoreStarted){    safeDismissDialog(DLG_NO_CONNECTION);    safeDismissDialog(DLG_NO_WIFI);            }            }}}public static HashMap<String, String> obtainkey(){return keyHashMap;}public class AppCheckTask extends AppVerDetectingTask{public AppCheckTask(Activity context, String appName, String verName,int verCode, boolean showDialog) {super(context, appName, verName, verCode, showDialog);}@Overrideprotected void onUpdate() {}@Overrideprotected void onCancel() {}@Overrideprotected void onExit() {finish();}}private HashMap<String, String> getKeyWords(String param,Uri url){String keyString = url.getQueryParameter("q");if(keyString != null){            if (keyString.startsWith("pub:")) {                keyString = keyString.replace("pub:", "");             key = keyString.trim().replace("^\"|\"$", "");             key = key.replace("\"", ""); }else if(keyString.startsWith("pname:")){ key = keyString.replace("pname:", ""); param = "package_name"; }     }else {     key = url.getQueryParameter("id"); }Log.i(TAG, "key = " + key);keyHashMap.put(param, key);return keyHashMap;}}

原创粉丝点击