Java tutorial
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wehome.ctb.paintpanel; import java.io.InputStream; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.MenuItem; import com.wehome.ctb.paintpanel.constant.MsgWhat; import com.wehome.ctb.paintpanel.plug.ImageGridFragment; import com.wehome.ctb.paintpanel.plug.ImageWallListFragment; import com.wehome.ctb.paintpanel.upgrade.AppUpgradeService; import com.wehome.ctb.paintpanel.util.EnumUtil; import com.wehome.ctb.paintpanel.util.NetWorkerUtil; import com.wehome.ctb.paintpanel.util.SettingUtility; import com.wehome.ctb.paintpanel.util.ToastMessageUtil; import com.wehome.ctb.paintpanel.util.VersionXmlService; /** * Demonstrates combining a TabHost with a ViewPager to implement a tab UI * that switches between tabs and also allows the user to perform horizontal * flicks to move between the tabs. */ @SuppressLint("NewApi") public class MainActivity extends SherlockFragmentActivity { TabHost mTabHost; ViewPager mViewPager; TabsAdapter mTabsAdapter; /* ??XML? */ Map<String, String> mHashMap; private String versioninfo = "http://download.soso88.org/version.xml"; private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); private String versionCode; @Override protected void onCreate(Bundle savedInstanceState) { //setTheme(PaintActivity.THEME); //Used for theme switching in samples setTheme(R.style.Theme_Sherlock); //requestWindowFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); mViewPager = (ViewPager) findViewById(R.id.pager); mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager); //?? if (!NetWorkerUtil.isNetworkAvailable(this)) { Toast.makeText(this, "?????", Toast.LENGTH_LONG).show(); return; } // ?? versionCode = MainApplication.mVersionCode; // fixedThreadPool.execute(new Runnable() { @Override public void run() { checkNewVersion(); // } }); //? Bundle bund = new Bundle(); bund.putInt(com.wehome.ctb.paintpanel.constant.PaintConst.BLASTS_TYPE_FLG, com.wehome.ctb.paintpanel.constant.PaintConst.BLASTS_TYPE); mTabsAdapter.addTab(mTabHost.newTabSpec("?").setIndicator("?"), ImageWallListFragment.class, bund); //? bund = new Bundle(); bund.putInt(com.wehome.ctb.paintpanel.constant.PaintConst.BLASTS_TYPE_FLG, com.wehome.ctb.paintpanel.constant.PaintConst.MY_TYPE); mTabsAdapter.addTab(mTabHost.newTabSpec("?").setIndicator("?"), ImageWallListFragment.class, bund); //?? /*bund = new Bundle(); bund.putInt(com.wehome.ctb.paintpanel.constant.PaintConst.BLASTS_TYPE_FLG, com.wehome.ctb.paintpanel.constant.PaintConst.BID_TYPE); mTabsAdapter.addTab(mTabHost.newTabSpec("").setIndicator(""), ImageGridFragment.class, bund);*/ // bund = new Bundle(); bund.putInt(com.wehome.ctb.paintpanel.constant.PaintConst.BLASTS_TYPE_FLG, com.wehome.ctb.paintpanel.constant.PaintConst.MY_FOLLOW); mTabsAdapter.addTab(mTabHost.newTabSpec("").setIndicator(""), ImageGridFragment.class, bund); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); } getOverflowMenu(); } /** * app ? * */ public void checkNewVersion() { // ?Messagewhat1 Message msg = Message.obtain(); msg.what = MsgWhat.USER_LOGIN_DIALOG_STAUTS; URL url;//version.xml // version.xml??? // ?XML XML?DOM?? VersionXmlService service = VersionXmlService.getInstance(); try { url = new URL(versioninfo);//version.xml? HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream inStream = connection.getInputStream();//??? mHashMap = service.loadVersionInfo(inStream); msg.obj = EnumUtil.Success; } catch (Exception e) { msg.obj = EnumUtil.ServerError; } // ???? handler.sendMessage(msg); } @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // ???? UI super.handleMessage(msg); switch (msg.what) { case MsgWhat.USER_LOGIN_DIALOG_STAUTS: if (msg.obj == EnumUtil.Success) { if (null != mHashMap) { String serviceCode = String.valueOf(mHashMap.get(VersionXmlService.VERSION_KEY)); String localVersion = String.valueOf(versionCode); // if (!serviceCode.toLowerCase().equals(localVersion.toLowerCase())) { isUpdate(); //? } } } break; default: break; } } }; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("tab", mTabHost.getCurrentTabTag()); } @Override public void onResume() { invalidateOptionsMenu(); //??? super.onResume(); } @Override public boolean onPrepareOptionsMenu(com.actionbarsherlock.view.Menu menu) { if (SettingUtility.getUid().equals("") || SettingUtility.getUid() == "") { return true; } else { // menu.getItem(0).setVisible(false); //login,??login ? menu.getItem(1).setIcon(getResources().getDrawable(R.drawable.account_loginout)); menu.getItem(1).setTitle(R.string.zx); return true; } } @Override public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) { getSupportMenuInflater().inflate(R.menu.main_pager_bar, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getTitle().equals(getResources().getString(R.string.paint_toolbar_speak))) { //speak(paintDrawImg); Intent i = new Intent(MainActivity.this, PaintActivity.class); startActivity(i); MainActivity.this.finish(); } else if (item.getTitle().equals(getResources().getString(R.string.main_toolbar_exit))) { //publish(paintDrawImg); this.finish(); } else if (item.getTitle().equals(getResources().getString(R.string.login_button_name))) { // Intent i = new Intent(MainActivity.this, LoginDialog.class); startActivity(i); } else if (item.getTitle().equals(getResources().getString(R.string.zx))) { // ? new AlertDialog.Builder(this).setTitle(R.string.zx_user) .setPositiveButton(R.string.alert_dialog_ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //? if (SettingUtility.removeAllEditor()) { SettingUtility.firstStart(); ToastMessageUtil.ToastMessage(MainActivity.this, R.string.zx_success); // Intent i = new Intent(MainActivity.this, LoginDialog.class); startActivity(i); } dialog.dismiss(); } }).setNegativeButton(R.string.alert_dialog_cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } return super.onOptionsItemSelected(item); } private void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { e.printStackTrace(); } } /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct paged in the ViewPager whenever the selected * tab changes. */ public static class TabsAdapter extends FragmentStatePagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final Context mContext; private final TabHost mTabHost; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { private final String tag; private final Class<?> clss; private final Bundle args; TabInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); mTabs.add(info); mTabHost.addTab(tabSpec); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public int getItemPosition(Object object) { return TabsAdapter.POSITION_NONE; } @Override public Object instantiateItem(ViewGroup container, int position) { return super.instantiateItem(container, position); } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { Log.d("MainTab", "onPageScrolled,position:" + position + ",positionOffset:" + positionOffset + ",positionOffsetPixels:" + positionOffsetPixels); } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly // also takes care of putting focus on it when not in touch mode. // The jerk. // This hack tries to prevent this from pulling focus out of our // ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } @Override public void onPageScrollStateChanged(int state) { Log.d("MainTab", "state:" + state); } } /** * * @return */ @SuppressLint("NewApi") private void isUpdate() { // ??? new AlertDialog.Builder(this, R.style.loading_dialog).setTitle(R.string.check_new_version_title) .setMessage(R.string.check_new_version) .setPositiveButton(R.string.alert_dialog_ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(MainActivity.this, AppUpgradeService.class); intent.putExtra("downloadUrl", mHashMap.get(VersionXmlService.URL_KEY)); intent.putExtra("appName", mHashMap.get(VersionXmlService.NAME_KEY) + ".apk"); startService(intent); } }).setNegativeButton(R.string.alert_dialog_cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } }