SoftrightApp.java :  » App » aiphonele » com » softright » Android Open Source

Android Open Source » App » aiphonele 
aiphonele » com » softright » SoftrightApp.java
package com.softright;

import static com.softright.Constants.PRES_CACHE;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;

import com.softright.activity.ThreeWebViewControlActivity;
import com.softright.interfaces.CallBackInterface;
import com.softright.interfaces.TimeoutInterface;
import com.softright.tools.LocalInfo;
import com.softright.tools.LocalMethod;
import com.softright.tools.Timmer;
import com.softright.tools.Utils;

@SuppressWarnings("unused")
public class SoftrightApp extends Activity implements Runnable, CallBackInterface {

  // @Override
  // protected void onResume() {
  // SoftrightApp.getApp().finish();
  // Intent newIntentIn = new Intent();
  // Log.d("UI","onResume three");
  // newIntentIn.setClass(SoftrightApp.getApp(),
  // ThreeWebViewControlActivity.class);
  // newIntentIn.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  // SoftrightApp.getApp().startActivity(newIntentIn);
  // super.onResume();
  // }

  @Override
  protected void onStart() {
    super.onStart();
    try {
      this.init();
    } catch (IOException e1) {
    }
  }

  @Override
  protected void onRestart() {
    super.onRestart();
    Log.d("UI", "softrightApp.onRestart.");
  }

  public void setWebView(boolean isWebView) {
    this.isWebView = isWebView;
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.d("telephony", "onKeyPressed keycode back in SoftrightApp");
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
      android.os.Process.killProcess(android.os.Process.myPid());
      if (isWebView) {
        SoftrightApp.getApp().setContentView(ui);
        isWebView = false;
        return true;
      }
    }
    return ui.onKeyDown(keyCode, event);
  }

  private boolean isWebView = false;
  // 
  public static UI ui = null;
  public static int SESSION_SHORTTIME = 60000;
  public static int BUTTON_TIME = 3000;
  public static int CTRL_TIME = 500;
  public static int EDIT_TIME = 1000;

  @Override
  public void onReceiveData(byte[] body, Hashtable<String, String> header, RequestData requestData) {
    if (body.length == 0) {
      if (requestData.handle != null)
        requestData.handle.fail(requestData);
      return;
    }

    String strId = header.get("sid");
    String strPackNum = header.get("PackNum");
    String strSn = header.get("sn");
    String strCrc = header.get("crc");
    if (strId == null)
      return;
    int nSessionID = (strId == null) ? 0 : Integer.parseInt(strId, 16);
    boolean bTimeout = requestData.server.sessionId != 0 && nSessionID == 0;
    //
    if (requestData.server.sessionId == 0 || nSessionID == 0) {
      requestData.server.sessionId = nSessionID;
      requestData.server.sessionId = nSessionID;

      if (strSn != null)
        requestData.server.random = (int) Long.parseLong(strSn, 16);

    }
    if ((nSessionID == -1 || nSessionID == 0 || nSessionID != requestData.server.sessionId || nSessionID == 0xffffffff) && bTimeout) {
      requestData.server.sessionId = 0;
      return;
    }
    int packNum = Integer.parseInt(strPackNum);
    int nIndex = 0;
    ByteArrayInputStream stream = new ByteArrayInputStream(body);
    for (int j = 0; j < packNum; j++) {

      try {
        if (!onReceive(stream, body, body.length, requestData))
          break;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }

  public boolean onReceive(ByteArrayInputStream stream, byte[] body, int nLen, RequestData requestData) throws Exception {
    try {
      if (requestData.bPreCache)
        return false;
      int nHeadLen = Utils.ReadInt(stream, 2);
      int nType = Utils.ReadInt(stream, 4); // type
      int nPage = Utils.ReadInt(stream, 4); // page
      int nActive = Utils.ReadInt(stream, 4); // active time
      int nLength = Utils.ReadInt(stream, 4); // data len
      if (requestData.handle != null) {
        byte[] data = new byte[nLength];
        stream.read(data);
        requestData.handle.handle(nType, nPage, nActive, nLength, data, requestData);
        return true;
      }
      if (!requestData.bCache && nActive > 0 || requestData.bPreCache) {
        if (nActive >= PRES_CACHE) {
          // Cache

          this.addDiskCache(requestData.url, body, (int) (System.currentTimeMillis() / 1000 + nActive), true);
        } else {
          // Cache

          this.addMemoCache(requestData.url, body, new Integer((int) (System.currentTimeMillis() / 1000 + nActive)), new Boolean(requestData.bPreCache));
        }
      }
      switch (nType & Constants.DATA_TYPE_MASK) {
      case Constants.DATA_TYPE_COOKIE:
        readCookiePackage(stream);
        return true;
      }
      boolean bDlg = Utils.Is(nType, Constants.DATA_SHOW_DLG, Constants.DATA_SHOWTYPE_MASK);
      if (bDlg) {

        if (nLength <= 0) {
          boolean bWantRefresh = Utils.Is(nType, Constants.TEXT_REFRESH);
          if (nPage != ui.getCurView().getPageId()) {
            if (ui.getPageStackPos(nPage) != -1 && !bWantRefresh) {
              ui.popStackTo(nPage);
            } else
              ui.setView(nPage, bWantRefresh);
          } else {
            if (bWantRefresh) {
              ui.setView(nPage, true);
            }
          }
          return true;
        }
      }
      boolean bChagePage = false;
      if (!bDlg && isViewData(nType) && Utils.Is(requestData.nRequestType, Constants.REQUEST_TYPE_AREA_MAIN, Constants.REQUEST_TYPE_AREA_MASK)) {
        if (ui.getCurView() != null && nPage != ui.getCurView().getPageId() && ((nType & Constants.DATA_TYPE_MASK) != Constants.DATA_TYPE_RES)) {
          bChagePage = true;
          if (ui.isRequestHasIndex())
            ui.pushToStack();
          ui.setView(nPage, false);
          if ((nPage != ui.getCurView().getPageId())) {
            stream.skip(nLength);
            return true;
          }
        }
        ui.setRequestHasIndex(false);
      }
      if (nLength <= 0 && ((nType & Constants.DATA_TYPE_MASK) != Constants.DATA_TYPE_DES)) {
        return true;
      }
      boolean bMsg = false;
      String strMsg = null;
      String strTitle = null;
      switch (nType & Constants.DATA_TYPE_MASK) {
      case Constants.DATA_TYPE_TEXT: // = 0X000001; //Text //
      {
        strTitle = Utils.ReadUTF(stream);
        String strContent = Utils.ReadUTF(stream);

        if (!bDlg) {
          ui.setView(nPage, false);
          if (!Utils.Is(requestData.nRequestType, Constants.REQUEST_TYPE_AREA_STATUS, Constants.REQUEST_TYPE_AREA_MASK)) {
            ui.OnReceiveTextData(nType, nPage, strTitle, strContent);
          }
        } else {
          ui.setView(nPage, false);
          ui.showDialog(strTitle, strContent);
        }
      }
        break;

      case Constants.DATA_TYPE_LOGIN: {
        byte bStatus = (byte) Utils.ReadInt(stream, 1);
        strMsg = Utils.ReadUTF(stream); // 2y + y
        bMsg = (strMsg != null);
        int nSize = Utils.ReadInt(stream, 2); // 2  2x +
        if ((nSize > 0) && (nLen >= nSize + 3)) {
          int nLenPassport = Utils.ReadInt(stream, 2);
          Constants.szPassport = new byte[nLenPassport];
          stream.read(Constants.szPassport, 0, nLenPassport);
          int nValidTime = Utils.ReadInt(stream, 4);
          int nCur = (int) (System.currentTimeMillis() / (1000));
          Constants.passportExpire = nValidTime + nCur;
          writePassport();
        }
        if (bMsg) {
          ui.showDialog("", strMsg);
          return true;
        }
        if (this.lstResNotFound.size() > 0) {
          ui.requestRes(true);
        }
        showUI();
        return true;
      }
      default:
        return true;
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  private static boolean isViewData(int nType) {
    return (((Constants.DATA_TYPE_MASK & nType) != Constants.DATA_TYPE_COOKIE) && ((Constants.DATA_TYPE_MASK & nType) != Constants.DATA_TYPE_DES)
        && ((Constants.DATA_TYPE_MASK & nType) != Constants.DATA_TYPE_RES) && ((Constants.DATA_TYPE_MASK & nType) != Constants.DATA_TYPE_LOGIN));
  }

  private void readCookiePackage(InputStream stream) throws Exception {
    int nCookieNum = Utils.ReadInt(stream, 2);
    for (int i = 0; i < nCookieNum; i++) {
      Cookie c = readCookieInfo(stream);
      removeOld(c.id);
      lstCookies.add(c);
    }
    this.writeCookies();
  }

  private Cookie readCookieInfo(InputStream stream) throws Exception {
    Cookie cookie = new Cookie();
    Utils.ReadInt(stream, 2);
    cookie.id = (Utils.ReadInt(stream, 4));
    int nCookieTimeOut = Utils.ReadInt(stream, 4);
    cookie.expire = ((int) (System.currentTimeMillis() / 1000) + nCookieTimeOut);

    cookie.name = new String(Utils.ReadByteArray(stream));
    byte[] value = Utils.ReadByteArray(stream);
    if (value != null)
      cookie.value = new String(value);// .trim();
    int[] szMask = new int[Utils.ReadInt(stream, 1)];
    for (int j = 0; j < szMask.length; j++) {
      szMask[j] = Utils.ReadInt(stream, 4);
    }
    cookie.mask = szMask;
    int szPage[] = new int[Utils.ReadInt(stream, 1)];
    for (int j = 0; j < szPage.length; j++) {
      szPage[j] = Utils.ReadInt(stream, 4);
    }
    cookie.page = szPage;

    return cookie;

  }

  private void removeOld(int id) {
    for (int j = 0; j < this.lstCookies.size(); j++) {
      Cookie c = lstCookies.get(j);
      if (c.id == id) {
        lstCookies.remove(j);
      }
    }
  }

  public Map<String, Integer> m_mapDiskCache = new HashMap<String, Integer>();
  public List<String> m_vctDiskCache = new ArrayList<String>(Constants.DISK_CACHE_SIZE);

  public void addDiskCache(String strUrl, byte[] szData, Integer nActive, boolean bWrite) {
    if (m_mapDiskCache.get(strUrl) != null) {
      return;
    }
    if (m_vctDiskCache.size() > Constants.DISK_CACHE_SIZE) {
      this.removeDiskCache(m_vctDiskCache.get(0));
      m_vctDiskCache.remove(0);
    }

    if (bWrite) {
      try {
        Utils.WriteBufToFile(this, "DC" + strUrl.hashCode(), szData, 0, szData.length);
        m_mapDiskCache.put(strUrl, nActive);
        m_vctDiskCache.add(strUrl);
      } catch (Exception e) {

      }
    }
    writeDiskCache();
  }

  public void removeDiskCache(String strUrl) {
    if (Utils.DeleteFile(this, "DC" + strUrl.hashCode())) {
      m_mapDiskCache.remove(strUrl);
      writeDiskCache();
    }
  }

  public boolean writeDiskCache() {
    try {

      ByteArrayOutputStream btaCache = new ByteArrayOutputStream(2048);
      Utils.WriteInt(btaCache, m_mapDiskCache.size(), 2);
      int count = 0;
      for (int i = 0; i < m_vctDiskCache.size(); i++) {

        String strKey = m_vctDiskCache.get(i);
        Integer nActive = (Integer) m_mapDiskCache.get(strKey);
        if (nActive != null) {
          Utils.WriteUTF(btaCache, strKey);
          Utils.WriteInt(btaCache, nActive.intValue(), 4);
        }
      }
      Utils.WriteBufToFile(this, "PageCache", btaCache.toByteArray(), 0, btaCache.size());
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  public void clearDiskCache() {
    m_mapDiskCache.clear();
    m_vctDiskCache.clear();
  }

  public void initDiskCache() {
    clearDiskCache();
    try {
      byte[] szCache = Utils.ReadFileToBuf(this, "PageCache");
      ByteArrayInputStream baiCache = new ByteArrayInputStream(szCache);
      int nLen = Utils.ReadInt(baiCache, 2);
      String strKey = null;
      boolean bNeedWrite = false;
      for (int i = 0; i < nLen; i++) {
        strKey = Utils.ReadUTF(baiCache);
        m_vctDiskCache.add(strKey);
        // byte[] szData=Tools.ReadByteArray(baiCache);
        int nActive = Utils.ReadInt(baiCache, 4);
        if (nActive > (int) (System.currentTimeMillis() / 1000))
          m_mapDiskCache.put(strKey, new Integer(nActive));
        else
          bNeedWrite = true;
      }
      if (bNeedWrite)
        writeDiskCache();
    } catch (Exception e) {

    }
  }

  public Map<String, Object[]> m_mapMemoCache = new HashMap<String, Object[]>();
  public String[] m_szMemoCache = new String[Constants.MEMO_CACHE_SIZE];
  private int m_nMemoCache = 0;

  public void addMemoCache(String strUrl, byte[] szData, int nActive, boolean bCheckExpire) {
    Object[] szCache = new Object[3];
    szCache[0] = nActive;
    szCache[1] = szData;
    szCache[2] = bCheckExpire;
    if (m_mapMemoCache.get(strUrl) != null) {
      // System.out.println(""+strUrl);
      m_mapMemoCache.put(strUrl, szCache);
      return;
    }
    m_nMemoCache++;
    if (m_nMemoCache >= m_szMemoCache.length)
      m_nMemoCache = 0;
    if (m_szMemoCache[m_nMemoCache] != null) {
      m_mapMemoCache.remove(m_szMemoCache[m_nMemoCache]);
    }
    m_szMemoCache[m_nMemoCache] = strUrl;
    m_mapMemoCache.put(strUrl, szCache);
  }

  public void clearMemoCacheFile() {
    try {
      File[] files = this.getFilesDir().listFiles(new MemoryCacheFilter());

      for (int i = 0; i < files.length; i++) {
        files[i].delete();
      }
    } catch (Exception e) {

    }
  }

  @Override
  public void onReceiveMessage(int msgH, int msgL, RequestData requestData) {
    if (requestData.handle == null) {
      ui.showDialog("", ":" + Integer.toHexString(msgL));
    } else {
      requestData.handle.fail(requestData);
    }

  }

  public static int REALTIME_TIME = 10000;
  public static int REALTIME_TIME_STATUS = 10000;

  public static final int TIMER_SESSION = 0x11;
  public static final int TIMER_BUTTON = 0x12;
  public static final int TIMER_CTRLSEND = 3;
  public static final int TIMER_REALTIME = 4;
  public static final int TIMER_EDIT = 5;
  public static final int TIMER_STATUS_BAR = 6;

  private static final int TIME_DIFF = 500; // debug 1000,RELEASE 30
  // private static Timer m_pTimer;
  // public static MyTimer m_pThis;
  // 
  // ID,

  public static final String APP_NAME = "hcrt";

  // private static InputTestView inputTextView;
  private List<String> lstRequestRes = new ArrayList<String>();

  private static SoftrightApp app = null;
  private boolean alreadyStarted = false;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    app = this;
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    // WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
    
    Constants.dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(Constants.dm);
    alreadyStarted = ui != null;
    if (ui == null)
      ui = new UI(this);
    if (!alreadyStarted) {
      Constants.SYS_RUNNING = true;
      new Thread(this).start();

    } else {
      try {
        ui = (UI) ui.clone();
        ui.setRunning(true);
        CThreadPool.getThread().setRunner(ui);
      } catch (CloneNotSupportedException e) {
      }

      this.setContentView(ui);
      ui.invalidate();
    }

  }

  public static UI getUI() {
    return ui;
  }

  private static List<Timmer> lstTimmer = new Vector<Timmer>();

  protected static synchronized void setTimer(int nID, int nTime, TimeoutInterface timmerListener) {
    synchronized (lstTimmer) {
      int nPos = FindTimerPos(nID);
      if (nPos >= 0)
        Remove(nPos);
      if (nTime < 0)
        return;

      Timmer timmer = new Timmer();
      timmer.id = nID;
      timmer.time = System.currentTimeMillis() + nTime;
      timmer.obj = timmerListener;
      for (int i = 0; i < lstTimmer.size(); i++) {
        Timmer t = lstTimmer.get(i);
        if (t.time > timmer.time) {
          lstTimmer.add(i, timmer);
          return;
        }
      }
      lstTimmer.add(timmer);
    }
  }

  /**
   * 
   */
  public static void runTimer() {
    long lCurTime = System.currentTimeMillis();
    while (lstTimmer.size() > 0) {
      Timmer t = lstTimmer.get(0);

      if (lCurTime < t.time - TIME_DIFF) {
        return;
      }
      lstTimmer.remove(0);
      timeOut(t);
    }
  }

  public static void timeOut(Timmer t) {
    t.obj.timeout(t.id);
  }

  public static void SetSessionTimer(int nTime, TimeoutInterface time) {
    setTimer(TIMER_SESSION, nTime, time);
  }

  public static void SetButtonTimer(TimeoutInterface time) {
    setTimer(TIMER_BUTTON, BUTTON_TIME, time);
  }

  public static void SetCtrlTimer(TimeoutInterface time) {
    setTimer(TIMER_CTRLSEND, CTRL_TIME, time);
  }

  public static void SetRealtimeTimer(TimeoutInterface time) {
    setTimer(TIMER_REALTIME, REALTIME_TIME, time);
  }

  public static void SetStatusBarRealtimeTimer(TimeoutInterface time) {
    setTimer(TIMER_STATUS_BAR, REALTIME_TIME_STATUS, time);
  }

  public static void SetEditTimer(TimeoutInterface time) {
    setTimer(TIMER_EDIT, EDIT_TIME, time);
  }

  private static int FindTimerPos(int nID) {
    for (int i = 0; i < lstTimmer.size(); i++)
      if (lstTimmer.get(i).id == nID)
        return i;
    return -1;
  }

  private static void Remove(int i) {
    synchronized (lstTimmer) {
      lstTimmer.remove(i);
    }
  }

  public static SoftrightApp getApp() {
    return app;
  }

  public boolean isCookieValidate(Cookie cookie, int nPage, int nCmdId) {
    int nActive = cookie.expire;
    if ((System.currentTimeMillis() / 1000) > nActive) {
      return false;
    }
    int[] szMask = (int[]) cookie.mask;
    // m_nPageId = m_pUI.GetCurPageID();
    if (szMask != null) {
      for (int i = 0; i < szMask.length; i++) {
        if ((szMask[i] | Constants.serverMask & nPage) == szMask[i] || (szMask[i] | Constants.serverMask & nCmdId) == szMask[i])
          return true;
      }
    }
    // System.out.println(m_nPageId);
    int[] szPage = (int[]) cookie.page;
    if (szPage != null) {
      for (int i = 0; i < szPage.length; i++) {
        // System.out.println(szPage[i]);
        if (szPage[i] == nPage || szPage[i] == nCmdId)
          return true;
      }

    }
    return false;
  }

  public Cookie getCookieById(int id) {
    for (int i = 0; i < this.lstCookies.size(); i++) {
      Cookie cookie = lstCookies.get(i);
      if (cookie.id == id)
        return cookie;
    }
    return null;
  }

  public List<Cookie> getCookieByPage(int page) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (int i = 0; i < this.lstCookies.size(); i++) {
      Cookie cookie = lstCookies.get(i);

      if (this.isCookieValidate(cookie, page, page)) {

        cookies.add(cookie);
      }
    }
    return cookies;
  }

  public String getCookieUrl(int nPage, int nCmdId) {
    StringBuffer stbResult = new StringBuffer();
    boolean bFirst = true;
    for (int i = 0; i < this.lstCookies.size(); i++) {
      Cookie cookie = lstCookies.get(i);

      if (this.isCookieValidate(cookie, nPage, nCmdId)) {
        stbResult.append(bFirst ? "" : "&");
        stbResult.append(cookie.name);
        stbResult.append("=");
        stbResult.append(Utils.urlEncode(cookie.value.getBytes()));
        bFirst = false;

        // bFirst=false;
      }
    }
    return stbResult.toString();
  }

  public String GetRequestUrl(int nType, int nPage, int nCmdId) {
    StringBuffer strResult = new StringBuffer();
    strResult.append("pg=");
    strResult.append(nPage);
    strResult.append("&cmd=");
    strResult.append(nCmdId);
    return strResult.toString();
  }

  private List<Cookie> lstCookies = new ArrayList<Cookie>();

  public void readCookies() {
    // Cookie
    try {
      byte[] szCookieData = Utils.ReadFileToBuf(this, "Cookie");
      if (szCookieData != null && szCookieData.length > 0) {
        // Cookie
        ByteArrayInputStream bStream = new ByteArrayInputStream(szCookieData);
        int nCookieLen = Utils.ReadInt(bStream, 2);

        for (int i = 0; i < nCookieLen; i++) {
          Cookie cookie = new Cookie();
          cookie.id = new Integer(Utils.ReadInt(bStream, 4));
          cookie.expire = new Integer(Utils.ReadInt(bStream, 4));
          cookie.name = new String(Utils.ReadByteArray(bStream));
          byte[] szData = Utils.ReadByteArray(bStream);
          if (szData != null)
            cookie.value = new String(szData);
          int[] szMask = new int[Utils.ReadInt(bStream, 1)];
          for (int j = 0; j < szMask.length; j++) {
            szMask[j] = Utils.ReadInt(bStream, 4);
          }
          cookie.mask = szMask;
          int[] szPage = new int[Utils.ReadInt(bStream, 1)];
          for (int j = 0; j < szPage.length; j++) {
            szPage[j] = Utils.ReadInt(bStream, 4);
          }
          cookie.page = szPage;
          if (cookie.expire > (System.currentTimeMillis() / 1000)) {
            lstCookies.add(cookie);
          }
        }
      }
    } catch (Exception e) {
    }
  }

  public void writeCookies() {
    try {
      if (lstCookies != null && lstCookies.size() > 0) {
        ByteArrayOutputStream baoOut = new ByteArrayOutputStream(1024);
        int nNeedWrite = 0;
        for (int i = 0; i < lstCookies.size(); i++) {
          Cookie cookie = lstCookies.get(i);
          int nActive = cookie.expire;
          if ((System.currentTimeMillis() / 1000 + 3600) < nActive) {
            nNeedWrite++;
          }
        }
        Utils.WriteInt(baoOut, nNeedWrite, 2);
        for (int i = 0; i < lstCookies.size(); i++) {
          Cookie cookie = lstCookies.get(i);
          int nActive = cookie.expire;
          if ((System.currentTimeMillis() / 1000 + 3600) > nActive) {
            continue;
          }
          Utils.WriteInt(baoOut, cookie.id, 4);
          Utils.WriteInt(baoOut, cookie.expire, 4);
          Utils.WriteByteArray(baoOut, cookie.name.getBytes());
          Utils.WriteByteArray(baoOut, cookie.value.getBytes());
          int[] szMask = cookie.mask;
          if (szMask == null)
            szMask = new int[0];
          Utils.WriteInt(baoOut, szMask.length, 1);
          for (int j = 0; j < szMask.length; j++) {
            Utils.WriteInt(baoOut, szMask[j], 4);
          }
          int[] szPage = cookie.page;
          if (szPage == null)
            szPage = new int[0];
          Utils.WriteInt(baoOut, szPage.length, 1);
          for (int j = 0; j < szPage.length; j++) {
            Utils.WriteInt(baoOut, szPage[j], 4);
          }
        }
        Utils.WriteBufToFile(this, "Cookie", baoOut.toByteArray(), 0, baoOut.size());
      }
    } catch (Exception e) {
    }
  }

  private String resVer = "0";

  public synchronized void readNodes() {
    int nLen = 0;
    try {
      byte[] szBuffer = Utils.ReadFileToBuf(this, "resversion");
      if (szBuffer != null && szBuffer.length > 0) {
        resVer = Utils.ReadUTF(szBuffer, 0, szBuffer.length / 2);
      } else
        this.addNeedRequestRes(("ResVersion"));

      szBuffer = Utils.ReadFileToBuf(this, "pffffffff");
      if (szBuffer != null && szBuffer.length > 0) {
        ByteArrayInputStream is = new ByteArrayInputStream(szBuffer);
        nLen = Utils.ReadInt(is, 2);
        // 
        Constants.PALETTE = new int[nLen];
        for (int i = 0; i < nLen; i++) {
          Constants.PALETTE[i] = Utils.ReadInt(is, 4);
        }
        synchronized (Constants.servers) {
          Constants.servers.clear();
          Constants.serverMask = Utils.ReadInt(is, 4); // 
          int nCount = Utils.ReadInt(is, 2); // 
          for (int i = 0; i < nCount; i++) {
            ServerInfo si = new ServerInfo();
            si.id = Utils.ReadInt(is, 4); // ID
            si.mask = Utils.ReadInt(is, 4); // 

            si.name = Utils.ReadUTF(is); // 
            int nArraySize = Utils.ReadInt(is, 2); // 
            if (nArraySize <= 0)
              continue;
            String ayStr[][] = new String[nArraySize][];
            for (int j = 0; j < nArraySize; j++) {
              si.addServer(Utils.ReadUTF(is));
            }
            Constants.servers.put(si.id, si);
          }
        }
      } else { // 

        this.addNeedRequestRes(("ffffffff"));
        ServerInfo si = new ServerInfo(0, 0xff00, "ca");
        si.addServer(Constants.SERVER_ADDR);
        Constants.servers.put(si.id, si);
      }

      readPages(0);

    } catch (Exception e) {
    }
  }

  public void readPages(int nServerMask) {
    try {
      String strFileName = "p" + Integer.toHexString(nServerMask);
      byte[] szBuffer = Utils.ReadFileToBuf(this, strFileName);
      if (szBuffer == null)
        this.addNeedRequestRes(Integer.toHexString(nServerMask));
      readPages(szBuffer, 0);
    } catch (Exception e) {
      this.addNeedRequestRes(Integer.toHexString(nServerMask));
    }
  }

  public boolean loadNodesById(int nId) {
    if (Constants.servers == null)
      return false;

    synchronized (Constants.servers) {
      ServerInfo serverInfo = Constants.getServerInfo(nId);
      if (serverInfo == null)
        return false;
      int nSubMask = serverInfo.mask;
      int nFuncId = (nId & nSubMask) | (Constants.serverMask & nId);
      readPages(nFuncId);
    }
    return true;
  }

  public void SetSystemNodes() {

  }

  public void readPages(byte[] szBuffer, int nIndex) throws Exception {
    if (szBuffer != null && szBuffer.length > 0) {
      ByteArrayInputStream is = new ByteArrayInputStream(szBuffer, nIndex, szBuffer.length);
      int nNodeCount = Utils.ReadInt(is, 2);
      if (nNodeCount <= 0 || nNodeCount > 1024) {
        throw new Exception("null");
      }
      for (int i = 0; i < nNodeCount; i++) {
        CNode node = CNode.ReadObject(is);
        if (Utils.Is(node.m_nType, CNode.VIEW_MENU | CNode.MENU_HOTKEY, CNode.VIEW_MASK | CNode.MENU_TYPE_MASK)) {
          if (node.m_strName != null)
            Constants.hotkeys.put(node.m_strName.substring(1).toUpperCase(), node);
        }
        if (node != null) {
          Constants.nodes.put(new Integer(node.m_nIndex), node);

        }
      }
    } else
      throw new Exception("null");

  }

  private List<String> lstRequesting = null;
  private List<String> lstResNotFound = new ArrayList<String>();

  public void addNeedRequestRes(String resName) {
    if (lstRequesting != null && lstRequesting.contains(resName))
      return;
    if (!this.lstResNotFound.contains(resName))
      this.lstResNotFound.add(resName);
  }

  private void init() throws IOException {

    Log.d("UI", "SystemVersion:" + Utils.getSDKVersionNumber());

    
    this.readIMEIAndIMSI();
    LocalInfo li = new LocalInfo();
    li.getColumnData();
    Log.d("SyncContact", "the count of person in init: " + Constants.CPP_CONTACTINFO.size());
    File localxml;

    localxml = new File("/data/data/com.softright/shared_prefs/config.xml");
    Constants.SPF = getSharedPreferences("config", 0);
    if (!localxml.exists()) {
      localxml.mkdir();
      Constants.SPF.edit().putString("isFirst", "true").commit();
      Log.d("UI", "isFirst :true");
      Constants.SPF.edit().putString("TipsContent", ":@" + "\n" + ",@ ,,").commit();
      Constants.SPF.edit().putString("version", Constants.VERSION).commit();
      Constants.SPF.edit().putInt("systemVersion",  Utils.getSDKVersionNumber());
    }
    // readNodes();
    // readPassport();
    showUI();
    
  }

  public void readIMEIAndIMSI() {
    TelephonyManager tm = (TelephonyManager) this.getSystemService(SoftrightApp.TELEPHONY_SERVICE);
    Constants.IMEI = tm.getDeviceId();
    Log.d("UI", "IMEI:" + Constants.IMEI);
  }

  public boolean login() {
    RequestData rd = new RequestData();
    rd.requestId = ++Constants.REQUEST_SEQ;
    rd.server = Constants.getServerInfo(Constants.PGID_LOGIN);
    rd.nRequestType = 0;
    return true;
  }

  public String GetOpenSessionUrl(int nType, int nCmdId) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(Constants.getRequestUrl(Constants.PGID_LOGIN));
    buffer.append("pg=");
    buffer.append(Integer.toHexString(Constants.PGID_LOGIN));
    buffer.append("&tp=");
    buffer.append(Integer.toHexString(nType));
    buffer.append("&cmd=");
    buffer.append(Integer.toHexString(nCmdId));
    return buffer.toString();
  }

  private boolean wantConnect() {
    int nCur = (int) (System.currentTimeMillis() / (1000));
    if (Constants.passportExpire <= nCur)
      return true;
    if (Constants.szPassport == null)
      return true;
    if (resVer == null)
      return true;
    if (resVer.compareTo("0") <= 0)
      return true;
    if (Constants.nodes == null)
      return true;
    if (Constants.nodes.size() == 0)
      return true;
    return false;
  }

  public String getLoginPost() {
    StringBuffer strAsk = new StringBuffer(512);
    strAsk.append("appver=" + Constants.APP_VER);
    strAsk.append("&resver=" + this.resVer);
    strAsk.append(Constants.initPostStr);
    return strAsk.toString();
  }

  public synchronized void readPassport() {
    try {
      byte[] szBuf = Utils.ReadFileToBuf(this, Constants.PASSPORT);
      int nIndex = 0;
      int nPassLen = Utils.ConvertArrayToInt(szBuf, nIndex, 2);
      nIndex += 2;
      Constants.szPassport = new byte[nPassLen];
      System.arraycopy(szBuf, nIndex, Constants.szPassport, 0, nPassLen);
      nIndex += nPassLen;
      Constants.passportExpire = Utils.ConvertArrayToInt(szBuf, nIndex, 4);
      nIndex += 4;
    } catch (Exception e) {
      Constants.passportExpire = 0;
      Constants.szPassport = null;
    }
  }

  public void writePassport() {
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      Utils.WriteByteArray(out, Constants.szPassport);
      Utils.WriteInt(out, Constants.passportExpire, 4);
      out.flush();
      Utils.WriteBufToFile(this, Constants.PASSPORT, out.toByteArray(), 0, out.size());
    } catch (Exception e) {

    }
  }

  private Handler mHandler = new Handler();

  public void run() {

    try {
      
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  private void showUI() {

    mHandler.post(new Runnable() {

      public void run() {

        setContentView(ui);
      }
    });
    ui.setView(Constants.NEW_MAIN_PAGE_ID, true);
    
  }

  public class MemoryCacheFilter implements FileFilter {
    public boolean accept(File pathname) {

      return pathname.getName().startsWith("MC");
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (this.isFinishing()) {
      Constants.SYS_RUNNING = false;
      Log.d("UI", "system exit");

    }
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.