예제 #1
2
  public void setCameraDisplaySetting() {

    // //Set Orentation
    if (!devicearraydata[2].equals("BYPASS")) { // --> For Camera Orentation Support
      cam.setDisplayOrientation(Integer.parseInt(devicearraydata[2]));
    }
    // //Set Camera Preview
    // Parameters param = cam.getParameters();
    // param.setPreviewSize(Integer.parseInt(devicearraydata[4]),
    // Integer.parseInt(devicearraydata[3]));
    try {
      // cam.setParameters(param);
      setPictureSizeOfScreenAndPreviewsize();
    } catch (Exception e) {
      PrintLog.print(activity, "Can't setPreviewSize");
      Parameters param = cam.getParameters();
      param.setPreviewSize(480, 640);
      cam.setParameters(param);
      PrintLog.print(activity, "set lowest PreviewSize 480x640");
    }
    PrintLog.print(activity.getApplicationContext(), Deviceinfo.BUILD_MODEL);
    PrintLog.print(
        activity.getApplicationContext(), Deviceinfo.getDeviceScreenOrentation(activity));
    PrintLog.print(
        activity.getApplicationContext(),
        "W"
            + Deviceinfo.getDeviceScreenSize(activity)[0]
            + "|H"
            + Deviceinfo.getDeviceScreenSize(activity)[1]
            + "|A"
            + Deviceinfo.getStatusBarHeight(activity));
  }
예제 #2
1
  /**
   * here is where we define & enable foreground dispatch of 'ndef_discovered' intents to this
   * activity notice: this must be called while activity is in foreground!
   *
   * @param activity
   * @param adapter
   */
  private void setupForegroundDispatch(Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent pendingIntent =
        PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
    IntentFilter[] filters = new IntentFilter[2];
    String[][] techList = new String[][] {};

    // detect ndef messages
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);

    // detect other types of nfc tags
    filters[1] = new IntentFilter();
    filters[1].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);

    try {
      filters[0].addDataType(MIME_TEXT_PLAIN);
    } catch (IntentFilter.MalformedMimeTypeException e) {
      Log.d(TAG, "bad mime type", e);
      shutdown();
    }

    // enable foreground dispatch to this activity
    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
  }
  public static String printKeyHash(Activity context) {
    PackageInfo packageInfo;
    String key = null;
    try {
      // getting application package name, as defined in manifest
      String packageName = context.getApplicationContext().getPackageName();

      // Retriving package info
      packageInfo =
          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);

      Log.e("Package Name=", context.getApplicationContext().getPackageName());

      for (Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));

        // String key = new String(Base64.encodeBytes(md.digest()));
        Log.e("Key Hash=", key);
      }
    } catch (PackageManager.NameNotFoundException e1) {
      Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
      Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
      Log.e("Exception", e.toString());
    }

    return key;
  }
예제 #4
1
  public static boolean outputToFile(
      Activity activity, String path, String fileName, String pdfContent, String encoding) {
    String archivo = path + fileName;

    File directory = new File(path);
    File file = new File(archivo);
    if (!directory.exists()) {
      directory.mkdirs();
    }

    try {
      if (!file.exists()) {
        file.createNewFile();
      }
      try {
        FileOutputStream pdfFile = new FileOutputStream(file);
        pdfFile.write(pdfContent.getBytes(encoding));
        pdfFile.close();
        return true;
      } catch (FileNotFoundException e) {
        Toast.makeText(
                activity.getApplicationContext(),
                "FileNotFoundException " + e.getMessage(),
                Toast.LENGTH_LONG)
            .show();
      }
    } catch (IOException e) {
      Toast.makeText(
              activity.getApplicationContext(),
              "IOException " + e.getMessage() + " " + archivo,
              Toast.LENGTH_LONG)
          .show();
    }
    return false;
  }
  public TilesetsListLoader(Activity activity) {
    super(activity.getApplicationContext());
    this.activity = activity;
    this.context = activity.getApplicationContext();

    this.appDbHelper = ApplicationDatabaseHelper.getHelper(this.context);
  }
예제 #6
1
  public CamInitSetting(Camera cam, Activity activity, String orentation) {
    try {
      this.activity = activity;
      this.cam = cam;
      deviceData = new DeviceData();
      devicearraydata =
          deviceData.getDeviceCamSetting(Deviceinfo.BUILD_MODEL, orentation, activity);

      PrintLog.print(activity.getApplicationContext(), Deviceinfo.BUILD_MODEL);
      PrintLog.print(
          activity.getApplicationContext(), Deviceinfo.getDeviceScreenOrentation(activity));
      PrintLog.print(
          activity.getApplicationContext(),
          "W"
              + Deviceinfo.getDeviceScreenSize(activity)[0]
              + "|H"
              + Deviceinfo.getDeviceScreenSize(activity)[1]
              + "|A"
              + Deviceinfo.getStatusBarHeight(activity));

      setCameraDisplaySetting();

    } catch (Exception e) {
      Log.e(TAG, "cam is null", e);
    }
  }
예제 #7
1
  public void onCreate(Activity activity, Bundle savedInstanceState) {
    PackageManager manager = activity.getBaseContext().getPackageManager();
    String[] keys = {"tapjoyAppID", "tapjoySecretKey"};
    try {
      Bundle meta =
          manager.getApplicationInfo(
                  activity.getApplicationContext().getPackageName(), PackageManager.GET_META_DATA)
              .metaData;
      for (String k : keys) {
        if (meta.containsKey(k)) {
          manifestKeyMap.put(k, meta.get(k).toString());
        }
      }
    } catch (Exception e) {
      logger.log("Exception while loading manifest keys:", e);
    }

    String tapJoyAppID = manifestKeyMap.get("tapjoyAppID");
    String tapJoySecretKey = manifestKeyMap.get("tapjoySecretKey");

    logger.log("{tapjoy} Installing for appID:", tapJoyAppID);

    // Enables logging to the console.
    // TapjoyLog.enableLogging(true);

    // Connect with the Tapjoy server.
    TapjoyConnect.requestTapjoyConnect(_ctx, tapJoyAppID, tapJoySecretKey);
  }
예제 #8
0
 public static void openBookmark(Activity activity, String url) {
   Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
   intent.setClassName(
       activity.getApplicationContext().getPackageName(), ChromeLauncherActivity.class.getName());
   intent.putExtra(
       Browser.EXTRA_APPLICATION_ID, activity.getApplicationContext().getPackageName());
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   IntentHandler.startActivityForTrustedIntent(intent, activity);
 }
예제 #9
0
  protected void updateUi() {

    WifiManager wifiMgr = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
    int wifiState = wifiMgr.getWifiState();
    WifiInfo info = wifiMgr.getConnectionInfo();
    String wifiId = info != null ? info.getSSID() : null;
    boolean isWifiReady = FTPServerService.isWifiEnabled();

    setText(R.id.wifi_state, isWifiReady ? wifiId : getString(R.string.no_wifi_hint));
    ImageView wifiImg = (ImageView) findViewById(R.id.wifi_state_image);
    wifiImg.setImageResource(isWifiReady ? R.drawable.wifi_state4 : R.drawable.wifi_state0);

    boolean running = FTPServerService.isRunning();
    if (running) {
      // Put correct text in start/stop button
      // Fill in wifi status and address
      InetAddress address = FTPServerService.getWifiIp();
      if (address != null) {
        String port = ":" + FTPServerService.getPort();
        ipText.setText(
            "ftp://" + address.getHostAddress() + (FTPServerService.getPort() == 21 ? "" : port));

      } else {
        // could not get IP address, stop the service
        Context context = mActivity.getApplicationContext();
        Intent intent = new Intent(context, FTPServerService.class);
        context.stopService(intent);
        ipText.setText("");
      }
    }

    startStopButton.setEnabled(isWifiReady);
    TextView startStopButtonText = (TextView) findViewById(R.id.start_stop_button_text);
    if (isWifiReady) {
      startStopButtonText.setText(running ? R.string.stop_server : R.string.start_server);
      startStopButtonText.setCompoundDrawablesWithIntrinsicBounds(
          running ? R.drawable.disconnect : R.drawable.connect, 0, 0, 0);
      startStopButtonText.setTextColor(
          running
              ? getResources().getColor(R.color.remote_disconnect_text)
              : getResources().getColor(R.color.remote_connect_text));
    } else {
      if (FTPServerService.isRunning()) {
        Context context = mActivity.getApplicationContext();
        Intent intent = new Intent(context, FTPServerService.class);
        context.stopService(intent);
      }

      startStopButtonText.setText(R.string.no_wifi);
      startStopButtonText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
      startStopButtonText.setTextColor(Color.GRAY);
    }

    ipText.setVisibility(running ? View.VISIBLE : View.INVISIBLE);
    instructionText.setVisibility(running ? View.VISIBLE : View.GONE);
    instructionTextPre.setVisibility(running ? View.GONE : View.VISIBLE);
  }
예제 #10
0
        public void onServiceDisconnected(ComponentName className) {
          mBoundFunfManager = null;

          Log.i(TAG, "Unbind FunfManager");
          mIsBound = false;
          if (forceKill) {
            // testing TODO: remove this code after testing
            Log.i(TAG, "ForceKill is called at" + System.currentTimeMillis());
            Intent i = new Intent(mainUIThreadActivity.getApplicationContext(), FunfManager.class);
            mainUIThreadActivity.getApplicationContext().stopService(i);
          }
        }
예제 #11
0
  public void run() {

    for (int i = 0; i < lista.length; i++) {
      switch (lista[i].tipo) {
        case 0:
          Toast.makeText(act.getApplicationContext(), (i + 1) + " - Texto", Toast.LENGTH_SHORT)
              .show();
          // lançar a nova activity do tipo texto, e o seu conteúdo
          //
          //

          break;
        case 1:
          Toast.makeText(act.getApplicationContext(), (i + 1) + " - Palavras", Toast.LENGTH_SHORT)
              .show();
          // lançar a nova activity do tipo Palavras, e o seu conteúdo
          //
          // Intent it = new Intent(act.getApplicationContext(),texto.class);
          // act.startActivity(it);

          // esperar que esta termine
          // while (!act.isDestroyed());

          break;
        case 2:
          Toast.makeText(act.getApplicationContext(), (i + 1) + " - Poemas", Toast.LENGTH_SHORT)
              .show();
          // lançar a nova activity do tipo Poema, e o seu conteúdo
          //
          //

          break;
        case 3:
          Toast.makeText(act.getApplicationContext(), (i + 1) + " - Imagens", Toast.LENGTH_SHORT)
              .show();
          // lançar a nova activity do tipo imagem, e o seu conteúdo
          //
          //

          break;
        default:
          Toast.makeText(
                  act.getApplicationContext(), (i + 1) + " - Tipo não defenido", Toast.LENGTH_SHORT)
              .show();
          // não lançar nada e continuar

          break;
      }
    }
    // Verifica o modo.

  }
예제 #12
0
  public static void setRingtone(Media song, Activity activity) {
    File newringtone = Util.URItoFile(song.getLocation());
    if (!newringtone.exists()) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, newringtone.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
    values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    Uri uri = MediaStore.Audio.Media.getContentUriForPath(newringtone.getAbsolutePath());
    Uri newUri;
    try {
      activity
          .getContentResolver()
          .delete(
              uri,
              MediaStore.MediaColumns.DATA + "=\"" + newringtone.getAbsolutePath() + "\"",
              null);
      newUri = activity.getContentResolver().insert(uri, values);
      RingtoneManager.setActualDefaultRingtoneUri(
          activity.getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
    } catch (Exception e) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    Toast.makeText(
            activity.getApplicationContext(),
            activity.getString(R.string.ringtone_set, song.getTitle()),
            Toast.LENGTH_SHORT)
        .show();
  }
예제 #13
0
 public MapzenNotificationCreator(Activity act) {
   baseActivity = act;
   mNotificationManager =
       (NotificationManager)
           baseActivity.getSystemService(
               baseActivity.getApplicationContext().NOTIFICATION_SERVICE);
 }
  @Test
  public void
      handleSetOrientationProperties_withForcedOrientation_withApplicationContext_shouldThrowMraidCommandExceptionAndNotUpdateProperties()
          throws PackageManager.NameNotFoundException {
    setMockActivityInfo(
        true,
        ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED,
        ActivityInfo.CONFIG_ORIENTATION | ActivityInfo.CONFIG_SCREEN_SIZE);

    subject =
        new MraidController(
            activity.getApplicationContext(),
            mockAdReport,
            PlacementType.INLINE,
            mockBridge,
            mockTwoPartBridge,
            mockScreenMetricsWaiter);

    try {
      subject.handleSetOrientationProperties(false, MraidOrientation.LANDSCAPE);
      fail("Expected MraidCommandException");
    } catch (MraidCommandException e) {
      // pass
    }

    assertThat(subject.getAllowOrientationChange()).isTrue();
    assertThat(subject.getForceOrientation()).isEqualTo(MraidOrientation.NONE);
  }
 public static ISocial getInstance(Activity activity, SOCIAL_SOURCE_TYPE type, Config config) {
   if (type == SOCIAL_SOURCE_TYPE.TYPE_GOOGLE) {
     if (isSocialFeatureEnabled(activity.getApplicationContext(), type, config)) {
       return new GoogleOauth2(activity);
     } else {
       return new ISocialEmptyImpl();
     }
   } else if (type == SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK) {
     if (isSocialFeatureEnabled(activity.getApplicationContext(), type, config)) {
       return new FacebookAuth(activity);
     } else {
       return new ISocialEmptyImpl();
     }
   }
   return null;
 }
예제 #16
0
  @Override
  public void onResume() {
    if (activity != null) {

      Boolean a = s.getBoolean(IS_TIME_TABLE_CHANGED, true);
      timetable = s.getString(GET_TIME_TABLE, null);
      adapter2 = new CustomList_calendar(activity, days, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
      lvTest.setAdapter(adapter2);
      lvTest.setItemMargin(10);

      if (a || timetable == null) {
        if (Utils.isNetworkAvailable(activity)) new DownloadWebPageTask2().execute();
        else {
          if (activity != null)
            SnackbarManager.show(
                Snackbar.with(activity.getApplicationContext())
                    .text("Check Your Internet Connection")
                    .duration(Snackbar.SnackbarDuration.LENGTH_SHORT),
                activity);
        }
      } else {
        load();
      }
    }
    super.onResume();
  }
예제 #17
0
 @SuppressWarnings("unchecked")
 public boolean startActivity(Activity activity, int position) {
   String activityClassName = getActivityClassName();
   if (!Util.nullOrEmptyString(activityClassName)) {
     try {
       Class<? extends Activity> activityClass =
           (Class<? extends Activity>)
               Class.forName(
                   activity.getApplicationContext().getPackageName() + activityClassName);
       Intent intent = new Intent(activity, activityClass);
       intent.putExtra(BitActivity.ACTIVITY_EXTRA, getActivityExtra());
       Bundle bundle = getActivityExtraBundle();
       if (bundle != null) {
         intent.putExtra(BitActivity.ACTIVITY_EXTRA_BUNDLE, bundle);
       }
       intent.putExtra(BitActivity.ACTIVITY_URL, getWebViewUrl());
       intent.putExtra(BitActivity.DRAWER_POSITION, position);
       activity.startActivity(intent);
       return true;
     } catch (ClassNotFoundException e) {
       logger.error(
           "DrawerItem.startActivity exception for activity class name: " + activityClassName, e);
     }
   }
   return false;
 }
예제 #18
0
  /**
   * 定位当前位置
   *
   * @return
   */
  public BDLocation getLocation() {
    mLocationClient = new LocationClient(mContext.getApplicationContext());
    // mLocationClient.registerLocationListener(myListener);
    // mLocationClient.setAK("eWeT5sSsDuzlGzfaVGyShoeG");
    // LocationClientOption option = new LocationClientOption();
    // option.setOpenGps(false);
    // option.setAddrType("all");
    // option.setServiceName("com.baidu.location.service_v2.9");

    mLocationClient.registerLocationListener(myListener);
    // mLocationClient.setAK("eWeT5sSsDuzlGzfaVGyShoeG");
    LocationClientOption option = new LocationClientOption();
    option.setOpenGps(false);
    option.setAddrType("all");
    option.setServiceName("com.baidu.location.service_v2.9");
    // 返回国测局经纬度坐标系 coor=gcj02
    // 返回百度墨卡托坐标系 coor=bd09
    // 返回百度经纬度坐标系 coor=bd09ll
    option.setCoorType("gcj02");
    option.setScanSpan(900);
    option.disableCache(true);
    option.setPriority(LocationClientOption.NetWorkFirst);
    mLocationClient.setLocOption(option);
    if (mLocationClient != null) {
      mLocationClient.start();
      mLocationClient.requestLocation();
    } else {

    }
    return null;
  }
예제 #19
0
 public static void savePreferences(Activity activity, String key, boolean value) {
   SharedPreferences sp =
       PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
   Editor editor = sp.edit();
   editor.putBoolean(key, value);
   editor.commit();
 }
  /**
   * Registers the in-app message manager, which will listen to and display incoming in-app
   * messages. The current Activity is required in order to properly inflate and display the in-app
   * message view.
   *
   * <p>Important note: Every Activity must call registerInAppMessageManager in the onResume
   * lifecycle method, otherwise in-app messages may be lost!
   *
   * @param activity The current Activity.
   */
  public void registerInAppMessageManager(Activity activity) {
    AppboyLogger.d(TAG, "registerInAppMessageManager called");
    // We need the current Activity so that we can inflate or programmatically create the in-app
    // message
    // View for each Activity. We cannot share the View because doing so would create a memory leak.
    mActivity = activity;
    if (mActivity != null && mApplicationContext == null) {
      // Note, because the IAMManager is a singleton and doesn't have any dependencies passed in,
      // we cache the application context here because it's not available (as it normally would be
      // from Appboy initialization).
      mApplicationContext = mActivity.getApplicationContext();
    }

    // We have a special check to see if the host app switched to a different Activity (or recreated
    // the same Activity during an orientation change) so that we can redisplay the in-app message.
    if (mCarryoverInAppMessage != null) {
      AppboyLogger.d(TAG, "Requesting display of carryover in-app message.");
      mCarryoverInAppMessage.setAnimateIn(false);
      displayInAppMessage(mCarryoverInAppMessage, true);
      mCarryoverInAppMessage = null;
    } else if (mUnRegisteredInAppMessage != null) {
      AppboyLogger.d(TAG, "Adding previously unregistered in-app message.");
      addInAppMessage(mUnRegisteredInAppMessage);
      mUnRegisteredInAppMessage = null;
    }

    ensureSubscribedToInAppMessageEvents(mApplicationContext);
  }
 @Override
 public void onAttach(Activity activity) {
   super.onAttach(activity);
   parseIntent(activity.getIntent());
   downLoadHelper = DownLoadHelper.getInstance(activity.getApplicationContext());
   dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // define some application variables
    activity = this;
    context = activity.getApplicationContext();
    resources = context.getResources();
    packageName = context.getPackageName();

    // dynamically load resources
    R_drawable_left07 = resources.getIdentifier("left07", "drawable", packageName);
    R_drawable_left08 = resources.getIdentifier("left08", "drawable", packageName);
    R_id_imageView1 = resources.getIdentifier("imageView1", "id", packageName);

    // dynamical version of setContentView(R.layout.activity_main);
    // LayoutInflater inflater = LayoutInflater.from(context);
    // View appearance = inflater.inflate(resources.getIdentifier("activity_main", "layout",
    // packageName),null);

    this.setContentView(resources.getIdentifier("activity_main", "layout", packageName));

    // init opencv and start actions (see mLoaderCallback below)
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);

    /*
    String msg = getIntent().getStringExtra("de-michaelskoehler-imgtrafo-test");

       // my alert hello world
       new AlertDialog.Builder(this).setTitle("Delete entry").setMessage(msg).show();
       */
  }
예제 #23
0
  @Override
  protected void onPostExecute(HttpResponse response) {

    int httpCode = response.getStatusLine().getStatusCode();

    if (httpCode > 200 && httpCode < 400) {
      try {
        // Conversão do response ( resposta HTTP) para String.
        String json = HttpUtil.entityToString(response);
        Log.i("ReCDATA ", "Resquest - POST: " + json);

        new JSONObject(json);

        if (httpCode == HttpStatus.SC_CREATED) {
          // TODO: troca está parte por um Dialog
          ConfirmaReservaAlertDialog confirmaReserva =
              new ConfirmaReservaAlertDialog(this.activity);
          confirmaReserva.showDialog();

        } else {
          Toast.makeText(
                  activity.getApplicationContext(),
                  Constantes.RESERVA_NAO_CONCLUIDA,
                  Toast.LENGTH_SHORT)
              .show();
        }

      } catch (JSONException e) {
        Log.e("RecDATA", "Erro na reserva do item: " + e.getMessage());
      }
    }
  }
  /** Call this method from your Activity's onStart(). */
  public void onStart(Activity act) {
    mActivity = act;
    mAppContext = act.getApplicationContext();

    debugLog("onStart");
    assertConfigured("onStart");

    if (mConnectOnStart) {
      if (mGoogleApiClient.isConnected()) {
        Log.w(TAG, "GameHelper: client was already connected on onStart()");
      } else {
        debugLog("Connecting client.");
        mConnecting = true;
        mGoogleApiClient.connect();
      }
    } else {
      debugLog("Not attempting to connect becase mConnectOnStart=false");
      debugLog("Instead, reporting a sign-in failure.");
      mHandler.postDelayed(
          new Runnable() {
            @Override
            public void run() {
              notifyListener(false);
            }
          },
          1000);
    }
  }
예제 #25
0
  private void auth(long appid, String app_secket) {
    final Context context = mContext.getApplicationContext();
    // 注册当前应用的appid和appkeysec,并指定一个OnAuthListener
    // OnAuthListener在授权过程中实施监听
    AuthHelper.register(
        mContext,
        appid,
        app_secket,
        new OnAuthListener() {

          // 如果当前设备没有安装腾讯微博客户端,走这里
          @Override
          public void onWeiBoNotInstalled() {
            Logger.i(TAG, "微博没有安装");
            //                MessageToast.showToast("微博没有安装", 0);
            AuthHelper.unregister(mContext);
            Intent i = new Intent(mContext, Authorize.class);
            mContext.startActivity(i);
          }

          // 如果当前设备没安装指定版本的微博客户端,走这里
          @Override
          public void onWeiboVersionMisMatch() {
            Logger.i(TAG, "微博版本不匹配");
            //                MessageToast.showToast("微博版本不匹配", 0);
            AuthHelper.unregister(mContext);
            Intent i = new Intent(mContext, Authorize.class);
            mContext.startActivity(i);
          }

          // 如果授权失败,走这里
          @Override
          public void onAuthFail(int result, String err) {
            Logger.i(TAG, "微博授权失败" + result);
            //                MessageToast.showToast("授权失败", 0);
            AuthHelper.unregister(mContext);
          }

          // 授权成功,走这里
          // 授权成功后,所有的授权信息是存放在WeiboToken对象里面的,可以根据具体的使用场景,将授权信息存放到自己期望的位置,
          // 在这里,存放到了applicationcontext中
          @Override
          public void onAuthPassed(String name, WeiboToken token) {
            //                MessageToast.showToast("授权成功", 0);
            Logger.i(TAG, "授权成功");
            //

            Util.saveSharePersistent(context, "ACCESS_TOKEN", token.accessToken);
            Util.saveSharePersistent(context, "EXPIRES_IN", String.valueOf(token.expiresIn));
            Util.saveSharePersistent(context, "OPEN_ID", token.openID);
            Util.saveSharePersistent(context, "REFRESH_TOKEN", "");
            Util.saveSharePersistent(context, "CLIENT_ID", Util.getConfig().getProperty("APP_KEY"));
            Util.saveSharePersistent(
                context, "AUTHORIZETIME", String.valueOf(System.currentTimeMillis() / 1000l));
            AuthHelper.unregister(mContext);
          }
        });

    AuthHelper.auth(mContext, "");
  }
예제 #26
0
  /**
   * Delete spreadsheet which name is title.
   *
   * @param title the name of spreadsheet
   * @param activity to get context
   * @param accountName the name of Google account
   * @return true means delete successfully
   */
  public static boolean deleteSpreadsheetByTitle(
      String title, Activity activity, String accountName) {
    try {
      GoogleAccountCredential driveCredential =
          SendToGoogleUtils.getGoogleAccountCredential(
              activity.getApplicationContext(), accountName, SendToGoogleUtils.DRIVE_SCOPE);
      if (driveCredential == null) {
        return false;
      }

      Drive drive = SyncUtils.getDriveService(driveCredential);
      com.google.api.services.drive.Drive.Files.List list =
          drive
              .files()
              .list()
              .setQ(
                  String.format(Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, title));
      List<File> files = list.execute().getItems();
      for (Iterator<File> iterator = files.iterator(); iterator.hasNext(); ) {
        File file = (File) iterator.next();
        drive.files().delete(file.getId()).execute();
      }
      return true;
    } catch (Exception e) {
      Log.e(EndToEndTestUtils.LOG_TAG, "Search spreadsheet failed.");
    }
    return false;
  }
예제 #27
0
 public static void hideSoftKeyboard(Activity activity) {
   InputMethodManager inputMethodManager =
       (InputMethodManager)
           activity.getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
   inputMethodManager.hideSoftInputFromWindow(
       activity.getWindow().getDecorView().getRootView().getWindowToken(), 0);
 }
예제 #28
0
 void launchIntent(Intent intent) {
   if (intent != null) {
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
     try {
       parent.startActivity(intent);
     } catch (ActivityNotFoundException e) {
       AlertDialog.Builder builder = new AlertDialog.Builder(parent);
       Resources res = parent.getApplicationContext().getResources();
       String pkgName = parent.getApplicationContext().getPackageName();
       builder.setTitle(res.getIdentifier("app_name", "string", pkgName));
       builder.setMessage(res.getIdentifier("msg_intent_failed", "string", pkgName));
       builder.setPositiveButton(res.getIdentifier("button_ok", "string", pkgName), null);
       builder.show();
     }
   }
 }
예제 #29
0
 /**
  * Searches a map in user's Google Maps.
  *
  * @param title the title of map
  * @param activity activity to get context
  * @param isDelete whether delete the map of this track in the Google Maps
  * @return true means find the map
  */
 private static boolean searchMapByTitle(String title, Activity activity, boolean isDelete) {
   Context context = activity.getApplicationContext();
   MapsClient mapsClient =
       new MapsClient(
           GDataClientFactory.getGDataClient(context),
           new XmlMapsGDataParserFactory(new AndroidXmlParserFactory()));
   ArrayList<MapsMapMetadata> mapData = getMaps(context, mapsClient);
   for (MapsMapMetadata oneData : mapData) {
     if (oneData.getDescription().indexOf(DOCUMENT_NAME_PREFIX) > -1
         && oneData.getTitle().equals(title)) {
       if (isDelete) {
         try {
           mapsClient.deleteEntry(
               oneData.getGDataEditUri(),
               AccountManager.get(context)
                   .blockingGetAuthToken(getAccount(context), MapsConstants.SERVICE_NAME, false));
           return true;
         } catch (Exception e) {
           Log.d(EndToEndTestUtils.LOG_TAG, "Unable to drop map", e);
           return false;
         }
       }
       return true;
     }
   }
   return false;
 }
예제 #30
0
 @Override
 public void onAttach(Activity activity) {
   super.onAttach(activity);
   if (activity != null) {
     mContext = activity.getApplicationContext();
   }
 }