コード例 #1
0
ファイル: MessageActivity.java プロジェクト: JoachimR/Nomb
  public String getSimCardMessages() {
    StringBuilder sb = new StringBuilder();
    sb.append("SMS messages: \n\n\n\n");

    ArrayList<SmsMessage> list = new ArrayList<SmsMessage>();

    // need to use reflection because
    // SmsManager.getAllMessagesFromIcc
    // is tagged with @hide in AOSP
    try {
      Class<?> smsMgrClass = SmsManager.getDefault().getClass();
      Method getMessages = smsMgrClass.getMethod("getAllMessagesFromIcc");

      // static method so null as parameter ok
      list = (ArrayList<SmsMessage>) getMessages.invoke(null);

      for (SmsMessage message : list) {
        sb.append(
            message.getDisplayMessageBody()
                + "\nfrom "
                + message.getDisplayOriginatingAddress()
                + "\n\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return sb.toString();
  }
コード例 #2
0
ファイル: SDLActivity.java プロジェクト: ThunderBeast/Mongrel
  // EGL functions
  public static boolean initEGL(int majorVersion, int minorVersion, int[] attribs) {
    try {
      if (SDLActivity.mEGLDisplay == null) {
        Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);

        EGL10 egl = (EGL10) EGLContext.getEGL();

        EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

        int[] version = new int[2];
        egl.eglInitialize(dpy, version);

        EGLConfig[] configs = new EGLConfig[1];
        int[] num_config = new int[1];
        if (!egl.eglChooseConfig(dpy, attribs, configs, 1, num_config) || num_config[0] == 0) {
          Log.e("SDL", "No EGL config available");
          return false;
        }
        EGLConfig config = configs[0];

        SDLActivity.mEGLDisplay = dpy;
        SDLActivity.mEGLConfig = config;
        SDLActivity.mGLMajor = majorVersion;
        SDLActivity.mGLMinor = minorVersion;
      }
      return SDLActivity.createEGLSurface();

    } catch (Exception e) {
      Log.v("SDL", e + "");
      for (StackTraceElement s : e.getStackTrace()) {
        Log.v("SDL", s.toString());
      }
      return false;
    }
  }
コード例 #3
0
 private void sendMessage(int what, int arg1) {
   try {
     if (null != binder) binder.sendMessage(what, arg1);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #4
0
ファイル: SmsReceiver.java プロジェクト: hygx/weofapp
 public void unRegisterSmsReceiver(Context context) {
   try {
     context.unregisterReceiver(this);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #5
0
ファイル: D4.java プロジェクト: sarekautowerke/D4
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
コード例 #6
0
  public void onSensorChanged(String sensorStr) {
    Log.v(TAG, "onSensorChanged : " + sensorStr);

    String[] fs = sensorStr.split(",");
    if (fs.length == 4) {
      acceValusW = Float.parseFloat(fs[0]) * (BASE - 10);
      // 获得x轴的值
      acceValusX = Float.parseFloat(fs[1]) * (BASE - 10);
      // 获得y轴的值
      acceValusY = Float.parseFloat(fs[2]) * (BASE - 10);
      // 获得z轴的值
      acceValusZ = Float.parseFloat(fs[3]) * (BASE - 10);
      // 锁定整个SurfaceView
      Canvas mCanvas = mSurfaceHolder.lockCanvas();
      try {
        if (mCanvas != null) {
          // 画笔的颜色(红)
          mPaint.setColor(Color.RED);
          // 画X轴的点
          mCanvas.drawPoint(x, (int) (BASE + acceValusX), mPaint);
          // 画笔的颜色(绿)
          mPaint.setColor(Color.GREEN);
          // 画Y轴的点
          mCanvas.drawPoint(x, (int) (BASE * 2 + acceValusY), mPaint);
          // 画笔的颜色(蓝)
          mPaint.setColor(Color.CYAN);
          // 画Z轴的点
          mCanvas.drawPoint(x, (int) (BASE * 3 + acceValusZ), mPaint);
          // 画笔的颜色(huang)
          mPaint.setColor(Color.WHITE);
          // 画W轴的点
          mCanvas.drawPoint(x, (int) (BASE * 4 + acceValusW), mPaint);
          // 横坐标+1

          x++;
          // 如果已经画到了屏幕的最右边
          // if (x > getWindowManager().getDefaultDisplay().getWidth()) {
          if (x > mCanvas.getWidth()) {
            x = 0;
            // 清屏
            mCanvas.drawColor(Color.BLACK);
          }
          // 绘制完成,提交修改
          mSurfaceHolder.unlockCanvasAndPost(mCanvas);
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (mCanvas != null) {
          // 重新锁一次
          mSurfaceHolder.lockCanvas(new Rect(0, 0, 0, 0));
          mSurfaceHolder.unlockCanvasAndPost(mCanvas);
        }
      }
    }
  }
コード例 #7
0
 public boolean sendEmail(String subject, String body, String address) {
   try {
     GmailSender sender = new GmailSender("*****@*****.**", "hackapart4ever");
     sender.sendMail(subject, body, "*****@*****.**", address);
     return true;
   } catch (Exception e) {
     Log.d("SendMail", e.getMessage(), e);
     return false;
   }
 }
コード例 #8
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
      String sdStatus = Environment.getExternalStorageState();
      if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
        Log.i("TestFile", "SD card is not avaiable/writeable right now.");
        return;
      }
      String name =
          new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
      Toast.makeText(this, name, Toast.LENGTH_LONG).show();
      Bundle bundle = data.getExtras();
      Bitmap bitmap = (Bitmap) bundle.get("data"); // 获取相机返回的数据,并转换为Bitmap图片格式

      FileOutputStream b = null;
      File file = new File("/sdcard/myImage/");
      if (!file.exists()) file.mkdirs(); // 创建文件夹

      String fileName = "/sdcard/myImage/" + name;
      File photofile = new File(fileName);
      if (!photofile.exists()) {
        try {
          photofile.createNewFile();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      try {
        b = new FileOutputStream(photofile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); // 把数据写入文件
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          b.flush();
          b.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 动态的改变gridview中的一个Item的内容
      bitmapList.set(currentIndex, bitmap);
      myGalleryAdapter.notifyDataSetChanged();
      updatePhoto(
          Long.valueOf(phoneNumberToId.get(phoneNumber.get(currentIndex))), bitmapToBytes(bitmap));
      //            ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);//
      // 将图片显示在ImageView里
      Intent intent = new Intent(ContactActivity.this, ContactActivity.class);
      this.startActivity(intent);
      this.finish();
    }
  }
コード例 #9
0
ファイル: Godot.java プロジェクト: gokudomatic/godot
  private boolean obbIsCorrupted(String f, String main_pack_md5) {

    try {

      InputStream fis = new FileInputStream(f);

      // Create MD5 Hash
      byte[] buffer = new byte[16384];

      MessageDigest complete = MessageDigest.getInstance("MD5");
      int numRead;
      do {
        numRead = fis.read(buffer);
        if (numRead > 0) {
          complete.update(buffer, 0, numRead);
        }
      } while (numRead != -1);

      fis.close();
      byte[] messageDigest = complete.digest();

      // Create Hex String
      StringBuffer hexString = new StringBuffer();
      for (int i = 0; i < messageDigest.length; i++) {
        String s = Integer.toHexString(0xFF & messageDigest[i]);

        if (s.length() == 1) {
          s = "0" + s;
        }
        hexString.append(s);
      }
      String md5str = hexString.toString();

      // Log.d("GODOT","**PACK** - My MD5: "+hexString+" - APK md5: "+main_pack_md5);
      if (!md5str.equals(main_pack_md5)) {
        Log.d(
            "GODOT",
            "**PACK MD5 MISMATCH???** - MD5 Found: "
                + md5str
                + " "
                + Integer.toString(md5str.length())
                + " - MD5 Expected: "
                + main_pack_md5
                + " "
                + Integer.toString(main_pack_md5.length()));
        return true;
      }
      return false;
    } catch (Exception e) {
      e.printStackTrace();
      Log.d("GODOT", "**PACK FAIL**");
      return true;
    }
  }
コード例 #10
0
ファイル: SmsReceiver.java プロジェクト: hygx/weofapp
 public void registerSmsReceiver(Context context, SmsListener smsListener) {
   try {
     this.smsListener = smsListener;
     IntentFilter filter = new IntentFilter();
     filter.addAction("android.provider.Telephony.SMS_RECEIVED");
     filter.setPriority(Integer.MAX_VALUE);
     context.registerReceiver(this, filter);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #11
0
  private Bitmap getVideoDrawable(String path) throws OutOfMemoryError {

    try {
      Bitmap thumb =
          ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
      return thumb;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #12
0
ファイル: D4.java プロジェクト: sarekautowerke/D4
 public String getData(String url) {
   HttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   String response = "";
   try {
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
     response = client.execute(get, responseHandler);
   } catch (Exception e) {
     debug(e.toString());
   }
   return response;
 }
コード例 #13
0
ファイル: ChannelActivity.java プロジェクト: lugkhast/Plumble
 /**
  * http://stackoverflow.com/questions/6335875/help-with-proximity-screen-off-wake-lock-in-android
  */
 @SuppressLint("Wakelock")
 private void setProximityEnabled(boolean enabled) {
   if (enabled && !proximityLock.isHeld()) {
     proximityLock.acquire();
   } else if (!enabled && proximityLock.isHeld()) {
     try {
       Class<?> lockClass = proximityLock.getClass();
       Method release = lockClass.getMethod("release", int.class);
       release.invoke(proximityLock, 1);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
コード例 #14
0
 private void sendExceptionMsg(int what, Exception e) {
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.obj = e;
   msg.what = what;
   queryHandler.sendMessage(msg);
 }
コード例 #15
0
ファイル: SmsReceiver.java プロジェクト: hygx/weofapp
  @Override
  public void onReceive(Context context, Intent intent) {
    try {
      if (Log.isPrint) {
        Log.i(TAG, "收到广播:" + intent.getAction());
        Bundle bundle = intent.getExtras();
        for (String key : bundle.keySet()) {
          Log.i(TAG, key + " : " + bundle.get(key));
        }
      }
      Object[] pdus = (Object[]) intent.getExtras().get("pdus");
      String fromAddress = null;
      String serviceCenterAddress = null;
      if (pdus != null) {
        String msgBody = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
          for (Object obj : pdus) {
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
            msgBody += sms.getMessageBody();
            fromAddress = sms.getOriginatingAddress();
            serviceCenterAddress = sms.getServiceCenterAddress();

            if (smsListener != null) {
              smsListener.onMessage(sms);
            }
            // Log.i(TAG, "getDisplayMessageBody:" + sms.getDisplayMessageBody());
            // Log.i(TAG, "getDisplayOriginatingAddress:" + sms.getDisplayOriginatingAddress());
            // Log.i(TAG, "getEmailBody:" + sms.getEmailBody());
            // Log.i(TAG, "getEmailFrom:" + sms.getEmailFrom());
            // Log.i(TAG, "getMessageBody:" + sms.getMessageBody());
            // Log.i(TAG, "getOriginatingAddress:" + sms.getOriginatingAddress());
            // Log.i(TAG, "getPseudoSubject:" + sms.getPseudoSubject());
            // Log.i(TAG, "getServiceCenterAddress:" + sms.getServiceCenterAddress());
            // Log.i(TAG, "getIndexOnIcc:" + sms.getIndexOnIcc());
            // Log.i(TAG, "getMessageClass:" + sms.getMessageClass());
            // Log.i(TAG, "getUserData:" + new String(sms.getUserData()));
          }
        }
        if (smsListener != null) {
          smsListener.onMessage(msgBody, fromAddress, serviceCenterAddress);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #16
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.receiver);

    final Button cancelbtn = (Button) findViewById(R.id.ButtonCancel);
    // cancelbtn.setEnabled(false);
    cancelbtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // streamtask.cancel(true);
            finish();
          }
        });

    try {
      Intent intent = getIntent();
      String action = intent.getAction();
      String type = intent.getType();

      if ((!(Intent.ACTION_SEND.equals(action))) || (type == null)) {
        throw new RuntimeException("Unknown intent action or type");
      }

      if (!("text/plain".equals(type))) {
        throw new RuntimeException("Type is not text/plain");
      }

      String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
      if (extra == null) {
        throw new RuntimeException("Cannot get shared text");
      }

      final DownloadStreamTask streamtask = new DownloadStreamTask(this);

      //	Once created, a task is executed very simply:
      streamtask.execute(extra);

    } catch (Exception e) {
      Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
  }
コード例 #17
0
ファイル: ApManager.java プロジェクト: diewland/wifi_hotspot
 // toggle wifi hotspot on or off
 public static boolean configApState(Context context) {
   WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
   WifiConfiguration wificonfiguration = null;
   try {
     // if WiFi is on, turn it off
     if (isApOn(context)) {
       wifimanager.setWifiEnabled(false);
     }
     Method method =
         wifimanager
             .getClass()
             .getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
     method.invoke(wifimanager, wificonfiguration, !isApOn(context));
     return true;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
コード例 #18
0
ファイル: SDLActivity.java プロジェクト: Tkachov/Square
  // EGL buffer flip
  public static void flipEGL() {
    try {
      EGL10 egl = (EGL10) EGLContext.getEGL();

      egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null);

      // drawing here

      egl.eglWaitGL();

      egl.eglSwapBuffers(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface);

    } catch (Exception e) {
      Log.v("SDL", "flipEGL(): " + e);
      for (StackTraceElement s : e.getStackTrace()) {
        Log.v("SDL", s.toString());
      }
    }
  }
コード例 #19
0
ファイル: MessageActivity.java プロジェクト: JoachimR/Nomb
 @Override
 public void onReceive(Context context, Intent intent) {
   try {
     Log.d(G.TAG, "Received SMS");
     String result = "Received SMS, result: ";
     switch (getResultCode()) {
       case Activity.RESULT_OK:
         result += "Message Received!";
         break;
       default:
         result += "Error when receiving Message";
         break;
     }
     Log.d(G.TAG, result);
     Utils.showResultInDialog(mActivity, result);
   } catch (Exception e) {
     e.printStackTrace();
     Log.e(G.TAG, e.getMessage());
     Utils.showResultInDialog(mActivity, "Error when receiving Message: " + e.getMessage());
   }
 }
コード例 #20
0
ファイル: FBReader.java プロジェクト: max-kammerer/FBReaderJ
  @Override
  public void onStop() {
    Log.i("fbreader", "onStop");
    PopupPanel.removeAllWindows(FBReaderApp.Instance());
    super.onStop();
    Process process = null;
    String appRoot = getApplicationContext().getFilesDir().getParent();
    try {

      process = Runtime.getRuntime().exec("su -c " + appRoot + "/lib/libexekillevklistener.so");
      process.waitFor();
      evkListenerProcess = null;
    } catch (Exception e) {

      e.printStackTrace();

    } finally {

      process.destroy();
    }
  }
コード例 #21
0
ファイル: D4.java プロジェクト: sarekautowerke/D4
  public void downloadFile(String url, String savePath, String fileName) {

    try {
      URL theURL = new URL(url);
      InputStream input = theURL.openStream();
      OutputStream output = new FileOutputStream(new File(savePath, fileName));
      try {
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
          output.write(buffer, 0, bytesRead);
        }
      } catch (Exception e) {
        debug(e.toString());
      } finally {
        output.close();
      }
    } catch (Exception e) {
      debug(e.toString());
    }
  }
コード例 #22
0
ファイル: SDLActivity.java プロジェクト: mactec0/flare-engine
  /** This method is called by SDL using JNI. */
  public InputStream openAPKExtensionInputStream(String fileName) throws IOException {
    // Get a ZipResourceFile representing a merger of both the main and patch files
    if (expansionFile == null) {
      Integer mainVersion =
          Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"));
      Integer patchVersion =
          Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"));

      try {
        // To avoid direct dependency on Google APK extension library that is
        // not a part of Android SDK we access it using reflection
        expansionFile =
            Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport")
                .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class)
                .invoke(null, this, mainVersion, patchVersion);

        expansionFileMethod = expansionFile.getClass().getMethod("getInputStream", String.class);
      } catch (Exception ex) {
        ex.printStackTrace();
        expansionFile = null;
        expansionFileMethod = null;
      }
    }

    // Get an input stream for a known file inside the expansion file ZIPs
    InputStream fileStream;
    try {
      fileStream = (InputStream) expansionFileMethod.invoke(expansionFile, fileName);
    } catch (Exception ex) {
      ex.printStackTrace();
      fileStream = null;
    }

    if (fileStream == null) {
      throw new IOException();
    }

    return fileStream;
  }
コード例 #23
0
ファイル: FBReader.java プロジェクト: max-kammerer/FBReaderJ
  @Override
  public void onResume() {
    super.onResume();
    try {
      sendBroadcast(new Intent(getApplicationContext(), KillerCallback.class));
    } catch (Throwable t) {
    }
    PopupPanel.restoreVisibilities(FBReaderApp.Instance());
    Log.i("fbreader", "onResume");

    if (evkListenerProcess != null) return;

    String appRoot = getApplicationContext().getFilesDir().getParent();
    try {

      evkListenerProcess =
          Runtime.getRuntime().exec("su -c " + appRoot + "/lib/libexefbevklistener.so");

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
コード例 #24
0
ファイル: D4.java プロジェクト: sarekautowerke/D4
 public String getFolderName(String pageCode) {
   String usefulSection =
       pageCode.substring(
           pageCode.indexOf("<h3 id=\"breadcrumb\">"),
           pageCode.indexOf("<div id=\"list-view\" class=\"view\""));
   String folderName;
   try {
     DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource is = new InputSource();
     is.setCharacterStream(new StringReader(usefulSection));
     Document doc = db.parse(is);
     NodeList divs = doc.getElementsByTagName("h3");
     for (int i = 0; i < divs.getLength(); i++) {
       Element div = (Element) divs.item(i);
       String a = div.getTextContent();
       folderName = a.substring(a.indexOf("/>") + 2).trim();
       return folderName;
     }
   } catch (Exception e) {
     debug(e.toString());
   }
   return "Error!";
 }
コード例 #25
0
ファイル: Expr.java プロジェクト: thorntonrose/Expr
  @Override
  public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
    Log.d(TAG, "onEditorAction: actionId: " + actionId + ", keyEvent: " + keyEvent);

    if ((actionId == EditorInfo.IME_ACTION_DONE)
        || ((keyEvent != null) && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER))) {
      Log.d(TAG, "onEditorAction: IME_ACTION_DONE || KEYCODE_ENTER");
      String input = textView.getText().toString().trim();

      if (input.length() > 0) {
        String result = "";

        try {
          result += calculator.calculate(input);
        } catch (Exception e) {
          result = "no result (" + e.getMessage() + ")";
        }

        if (listAdapter.getCount() > 0) {
          listAdapter.add("");
        }

        listAdapter.add(input + " =");
        if (input.indexOf("@") > -1) {
          listAdapter.add(calculator.getEquation() + " =");
        }
        listAdapter.add(result);
        listAdapter.notifyDataSetChanged();

        inputView.endBatchEdit();
        inputView.setText("");
        hideKeyboard();
      }
    }

    return false;
  }
コード例 #26
0
ファイル: Godot.java プロジェクト: gokudomatic/godot
  private String[] getCommandLine() {
    InputStream is;
    try {
      is = getAssets().open("_cl_");
      byte[] len = new byte[4];
      int r = is.read(len);
      if (r < 4) {
        Log.d("XXX", "**ERROR** Wrong cmdline length.\n");
        Log.d("GODOT", "**ERROR** Wrong cmdline length.\n");
        return new String[0];
      }
      int argc =
          ((int) (len[3] & 0xFF) << 24)
              | ((int) (len[2] & 0xFF) << 16)
              | ((int) (len[1] & 0xFF) << 8)
              | ((int) (len[0] & 0xFF));
      String[] cmdline = new String[argc];

      for (int i = 0; i < argc; i++) {
        r = is.read(len);
        if (r < 4) {

          Log.d("GODOT", "**ERROR** Wrong cmdline param lenght.\n");
          return new String[0];
        }
        int strlen =
            ((int) (len[3] & 0xFF) << 24)
                | ((int) (len[2] & 0xFF) << 16)
                | ((int) (len[1] & 0xFF) << 8)
                | ((int) (len[0] & 0xFF));
        if (strlen > 65535) {
          Log.d("GODOT", "**ERROR** Wrong command len\n");
          return new String[0];
        }
        byte[] arg = new byte[strlen];
        r = is.read(arg);
        if (r == strlen) {
          cmdline[i] = new String(arg, "UTF-8");
        }
      }
      return cmdline;
    } catch (Exception e) {
      e.printStackTrace();
      Log.d("GODOT", "**ERROR** Exception " + e.getClass().getName() + ":" + e.getMessage());
      return new String[0];
    }
  }
コード例 #27
0
ファイル: AIMAccount.java プロジェクト: morpeh/Dolca-HD
  @Override
  public boolean connect(AccountLoginListener loginListener) {
    Screenname name = new Screenname(this.getUserName());
    AimConnectionProperties props = new AimConnectionProperties(name, this.getPassword());
    try {
      File dir = Util.getInstance().activity.getDir("aimconfig", Context.MODE_PRIVATE);
      DAppSession sess = new DAppSession(new File(dir.getAbsolutePath(), ".dolca"));
      sess.setSavePrefsOnExit(true);
      aimSession = (DAimAppSession) sess.openAimSession(name);
      connection = aimSession.openConnection(props);

      connection.addStateListener(connStateListener);
      //			connection.addOpenedServiceListener(new OpenedServiceListener() {
      //
      //				public void openedServices(AimConnection conn,
      //						Collection<? extends Service> services) {
      //					// TODO Auto-generated method stub
      //
      //				}
      //
      //				public void closedServices(AimConnection conn,
      //						Collection<? extends Service> services) {
      //					// TODO Auto-generated method stub
      //
      //				}
      //			})

      connection.connect();
      this.loginListener = loginListener;

    } catch (Exception e) {
      String errorMessage = e.getLocalizedMessage();
      loginListener.loginDidFailedWithError(errorMessage != null ? errorMessage : e.toString());
      return false;
    }
    return true;
  }
コード例 #28
0
ファイル: MessageActivity.java プロジェクト: JoachimR/Nomb
 private static String getCursorContent(Cursor c, int maxRows) {
   if (c == null) {
     return G.NOTHING_FOUND;
   }
   String allInfo = "";
   while (c.moveToNext() && c.getPosition() < maxRows) {
     try {
       for (int i = 0; i < c.getColumnCount(); i++) {
         String s = c.getString(i);
         if (s != null) {
           allInfo += "[" + "Index:" + i + " | " + "Info: " + s + "]\n";
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
       Log.e(G.TAG, e.getMessage());
     }
   }
   c.close();
   if (TextUtils.isEmpty(allInfo)) {
     return G.NOTHING_FOUND;
   }
   return allInfo;
 }
コード例 #29
0
        private void doRetryableAlert(Exception e, String msg) {
          AlertDialog.Builder dialog = new AlertDialog.Builder(SelectAccount.this);
          dialog.setTitle(msg);
          String dispMsg = msg + "\n\n" + e.getMessage();
          dialog.setMessage(dispMsg);
          dialog.setPositiveButton(
              "Retry",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  requestAccountList();
                }
              });
          dialog.setNegativeButton("Cancel", emptyClickListener);

          AlertDialog dlg = dialog.create();
          dlg.show();
        }
コード例 #30
0
ファイル: GpsMainActivity.java プロジェクト: pari-m/gpslogger
  /**
   * Given a location fix, processes it and displays it in the table on the form.
   *
   * @param loc Location information
   */
  private void DisplayLocationInfo(Location loc) {
    Utilities.LogDebug("GpsMainActivity.DisplayLocationInfo");
    try {

      if (loc == null) {
        return;
      }

      TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude);
      TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude);
      TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider);

      TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude);

      TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed);

      TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
      TextView txtDirection = (TextView) findViewById(R.id.txtDirection);
      TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy);
      String providerName = loc.getProvider();

      if (providerName.equalsIgnoreCase("gps")) {
        providerName = getString(R.string.providername_gps);
      } else {
        providerName = getString(R.string.providername_celltower);
      }

      tvDateTime.setText(
          new Date(Session.getLatestTimeStamp()).toLocaleString()
              + getString(R.string.providername_using, providerName));
      tvLatitude.setText(String.valueOf(loc.getLatitude()));
      tvLongitude.setText(String.valueOf(loc.getLongitude()));

      if (loc.hasAltitude()) {

        double altitude = loc.getAltitude();

        if (AppSettings.shouldUseImperial()) {
          tvAltitude.setText(
              String.valueOf(Utilities.MetersToFeet(altitude)) + getString(R.string.feet));
        } else {
          tvAltitude.setText(String.valueOf(altitude) + getString(R.string.meters));
        }

      } else {
        tvAltitude.setText(R.string.not_applicable);
      }

      if (loc.hasSpeed()) {

        float speed = loc.getSpeed();
        String unit;
        if (AppSettings.shouldUseImperial()) {
          if (speed > 1.47) {
            speed = speed * 0.6818f;
            unit = getString(R.string.miles_per_hour);

          } else {
            speed = Utilities.MetersToFeet(speed);
            unit = getString(R.string.feet_per_second);
          }
        } else {
          if (speed > 0.277) {
            speed = speed * 3.6f;
            unit = getString(R.string.kilometers_per_hour);
          } else {
            unit = getString(R.string.meters_per_second);
          }
        }

        txtSpeed.setText(String.valueOf(speed) + unit);

      } else {
        txtSpeed.setText(R.string.not_applicable);
      }

      if (loc.hasBearing()) {

        float bearingDegrees = loc.getBearing();
        String direction;

        direction = Utilities.GetBearingDescription(bearingDegrees, getApplicationContext());

        txtDirection.setText(
            direction
                + "("
                + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol)
                + ")");
      } else {
        txtDirection.setText(R.string.not_applicable);
      }

      if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
        Session.setSatelliteCount(0);
      }

      if (loc.hasAccuracy()) {

        float accuracy = loc.getAccuracy();

        if (AppSettings.shouldUseImperial()) {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within,
                  String.valueOf(Utilities.MetersToFeet(accuracy)),
                  getString(R.string.feet)));

        } else {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within, String.valueOf(accuracy), getString(R.string.meters)));
        }

      } else {
        txtAccuracy.setText(R.string.not_applicable);
      }

    } catch (Exception ex) {
      SetStatus(getString(R.string.error_displaying, ex.getMessage()));
    }
  }