コード例 #1
0
  public void setCropViewTileSource(
      final BitmapRegionTileSource.BitmapSource bitmapSource,
      final boolean touchEnabled,
      final boolean moveToLeft,
      final Runnable postExecute) {
    final Context context = WallpaperCropActivity.this;
    final View progressView = findViewById(R.id.loading);
    final AsyncTask<Void, Void, Void> loadBitmapTask =
        new AsyncTask<Void, Void, Void>() {
          protected Void doInBackground(Void... args) {
            if (!isCancelled()) {
              try {
                bitmapSource.loadInBackground();
              } catch (SecurityException securityException) {
                if (isDestroyed()) {
                  // Temporarily granted permissions are revoked when the activity
                  // finishes, potentially resulting in a SecurityException here.
                  // Even though {@link #isDestroyed} might also return true in different
                  // situations where the configuration changes, we are fine with
                  // catching these cases here as well.
                  cancel(false);
                } else {
                  // otherwise it had a different cause and we throw it further
                  throw securityException;
                }
              }
            }
            return null;
          }

          protected void onPostExecute(Void arg) {
            if (!isCancelled()) {
              progressView.setVisibility(View.INVISIBLE);
              if (bitmapSource.getLoadingState() == BitmapSource.State.LOADED) {
                mCropView.setTileSource(new BitmapRegionTileSource(context, bitmapSource), null);
                mCropView.setTouchEnabled(touchEnabled);
                if (moveToLeft) {
                  mCropView.moveToLeft();
                }
              }
            }
            if (postExecute != null) {
              postExecute.run();
            }
          }
        };
    // We don't want to show the spinner every time we load an image, because that would be
    // annoying; instead, only start showing the spinner if loading the image has taken
    // longer than 1 sec (ie 1000 ms)
    progressView.postDelayed(
        new Runnable() {
          public void run() {
            if (loadBitmapTask.getStatus() != AsyncTask.Status.FINISHED) {
              progressView.setVisibility(View.VISIBLE);
            }
          }
        },
        1000);
    loadBitmapTask.execute();
  }
コード例 #2
0
  protected void generateAsyncListMetadata() {
    synchronized (mObjectList) {
      if (mCurrentMetadataTask != null) {
        mCurrentMetadataTask.cancel(true);
      }

      final StickyHeaderListViewArrayAdapterBase<T, D> that = this;

      this.mCurrentMetadataTask =
          new AsyncTask<Void, Void, Void>() {
            private MetadataDTO metadata;

            @Override
            protected Void doInBackground(Void... params) {
              this.metadata = generateListMetadata();
              return null;
            }

            protected void onPostExecute(Void result) {
              mNotifiyng = true;
              that.mPrevHeadersPositionByIndex = metadata.getPrevHeadersPositionByIndex();
              that.mNextHeadersPositionByIndex = metadata.getNextHeadersPositionByIndex();
              that.mViewTypesByPosition = metadata.getViewTypesByPosition();
              that.mTotalItems = metadata.getTotalItems();

              StickyHeaderListViewArrayAdapterBase.super.notifyDataSetChanged();
            };
          };
      mCurrentMetadataTask.execute();
    }
  }
コード例 #3
0
  private void saveToSdcard() {
    GlobalVariables g = GlobalVariables.getInstance();
    String fullPath =
        g.getUserHomePath()
            + "userdata/"
            + g.getSubject()
            + "/"
            + g.getCollectname()
            + g.getDirectory()
            + "/UserPaint/"
            + Integer.toString(((CheckContext) context).GetCurrentPage())
            + ".png";

    File f = new File(fullPath);
    if (!f.getParentFile().exists()) {
      f.getParentFile().mkdirs();
    }

    if (bitmap != null) {
      try {
        AsyncTask at = new SaveBitmapAsyncTask(Bitmap.createBitmap(bitmap), fullPath);
        at.execute(new Object[] {});
      } catch (Exception e) {
        Toast.makeText(
                context,
                getResources().getString(R.string.tip_sava_failed) + fullPath,
                Toast.LENGTH_SHORT)
            .show();
        e.printStackTrace();
      }
    }
  }
コード例 #4
0
 public void getRegistrationID() {
   Log.d("KiiPushUnityPlugin", "#####getRegistrationID");
   AsyncTask<String, Void, Void> registerTask =
       new AsyncTask<String, Void, Void>() {
         @Override
         protected Void doInBackground(String... params) {
           String registrationId = "";
           String errorMessage = "";
           for (int retry = 0; retry < 3; retry++) {
             try {
               GoogleCloudMessaging gcm =
                   GoogleCloudMessaging.getInstance(UnityPlayer.currentActivity);
               registrationId = gcm.register(params[1]);
             } catch (Throwable e) {
               // Nothing to do.
               Log.d("KiiPushUnityPlugin", "#####Push register is failed");
               errorMessage = e.getMessage();
             }
             if (!registrationId.equals("")) {
               Log.d("KiiPushUnityPlugin", "#####Found RegistrationID : " + registrationId);
               break;
             }
           }
           if (TextUtils.isEmpty(registrationId)) {
             UnityPlayer.UnitySendMessage(params[0], "OnRegisterPushFailed", errorMessage);
           } else {
             UnityPlayer.UnitySendMessage(params[0], "OnRegisterPushSucceeded", registrationId);
           }
           return null;
         }
       };
   registerTask.execute(this.listenerGameObjectName, this.senderId);
 }
コード例 #5
0
  @Override
  public void onRefresh() {
    AsyncTask<Void, Void, Void> task =
        new AsyncTask<Void, Void, Void>() {
          @Override
          protected Void doInBackground(Void... params) {
            try {
              PrimaryUser.getInstance().refresh();
              model = user.getInventory();

            } catch (IOException e) {
              e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
              e.printStackTrace();
            }
            return null;
          }

          @Override
          protected void onPostExecute(Void aVoid) {
            model.setFilters(filters);
            adapter.notifyUpdated(model);
            mSwipeRefreshLayout.setRefreshing(false);
          }
        };
    task.execute();
  }
コード例 #6
0
 @Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
   if (log.isDebugEnabled()) {
     log.debug("onLayout ...");
   }
   super.onLayout(changed, l, t, r, b);
   if (changed && (headerLayoutParams == null)) {
     hideHeaderHeight = -header.getHeight();
     if (log.isDebugEnabled()) {
       log.debug("init Layout params, hideHeaderHeight :" + hideHeaderHeight);
     }
     headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
     headerLayoutParams.topMargin = hideHeaderHeight;
     if (!this.pendingTasks.isEmpty()) {
       for (AsyncTask<Void, Integer, Integer> task : this.pendingTasks) {
         task.execute();
       }
       this.pendingTasks.clear();
     }
   } else {
     if (log.isDebugEnabled()) {
       log.debug("onLayout, hideHeaderHeight :" + headerLayoutParams.topMargin);
     }
     // header.setLayoutParams(headerLayoutParams);
   }
 }
コード例 #7
0
  private void removeProductAsync(long productId) {
    final ProductRepository productRepository =
        RepositoryProvider.getInstance(getContext()).resolve(ProductRepository.class);
    AsyncTask<Long, Void, String> task =
        new AsyncTask<Long, Void, String>() {

          @Override
          protected String doInBackground(Long... params) {
            String errorMessage = null;
            long productId = params[0];

            try {
              productRepository.remove(productId);
            } catch (SQLException e) {
              e.printStackTrace();
            }

            return errorMessage;
          }

          @Override
          public void onPostExecute(String errorMessage) {
            if (!TextUtils.isEmpty(errorMessage)) {
              DialogHelper.showAlertDialog(getContext(), errorMessage);
            } else {
              EventBus.getDefault().post(new ProductSelectedEvent(null));
              EventBus.getDefault().post(new RefreshProductListEvent());
            }
          }
        };
    task.execute(productId);
  }
コード例 #8
0
  /** Asynchronous task for exporting the calendar to a local Google calendar */
  void exportCalendarToGoogle() {
    AsyncTask<Void, Void, Boolean> backgroundTask;

    backgroundTask =
        new AsyncTask<Void, Void, Boolean>() {
          @Override
          protected Boolean doInBackground(Void... params) {
            CalendarManager.syncCalendar(CalendarActivity.this);
            return true;
          }

          @Override
          protected void onPostExecute(Boolean result) {
            // Informs the user about the ongoing action
            if (!CalendarActivity.this.isFinishing()) {
              AlertDialog.Builder builder = new AlertDialog.Builder(CalendarActivity.this);
              builder
                  .setMessage(CalendarActivity.this.getString(R.string.dialog_show_calendar))
                  .setPositiveButton(
                      CalendarActivity.this.getString(R.string.yes), CalendarActivity.this)
                  .setNegativeButton(
                      CalendarActivity.this.getString(R.string.no), CalendarActivity.this)
                  .show();
              attachSectionPagerAdapter();
              showLoadingEnded();
            }
          }

          @Override
          protected void onPreExecute() {
            showLoadingStart();
          }
        };
    backgroundTask.execute();
  }
コード例 #9
0
  private void asyncAddAlarm(final Alarm alarm, final boolean showTimePicker) {
    final AsyncTask<Void, Void, Void> updateTask =
        new AsyncTask<Void, Void, Void>() {
          @Override
          protected Void doInBackground(Void... aVoid) {
            Alarms.addAlarm(AlarmClock.this, alarm);
            return null;
          }

          @Override
          protected void onPostExecute(Void aVoid) {
            if (alarm.enabled) {
              popToast(alarm);
            }
            mAdapter.setNewAlarm(alarm.id);
            scrollToAlarm(alarm.id);

            // We need to refresh the first view item because bindView may have been called
            // before setNewAlarm took effect. In that case, the newly created alarm will not be
            // expanded.
            View view = mAlarmsList.getChildAt(0);
            mAdapter.getView(0, view, mAlarmsList);
            if (showTimePicker) {
              AlarmUtils.showTimeEditDialog(AlarmClock.this.getFragmentManager(), alarm);
            }
          }
        };
    updateTask.execute();
  }
コード例 #10
0
  private void fetchMessages() {
    Log.d("LC", "Fetchign messages");
    AsyncTask task =
        new AsyncTask<Object, Void, JSONArray>() {
          @Override
          protected JSONArray doInBackground(Object[] params) {
            return LetsChatAPIClient.getInstance().getMessages(mRoomID);
          }

          @Override
          protected void onPostExecute(JSONArray jsonArray) {
            if (jsonArray == null) {
              return;
            }

            try {
              for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject message = jsonArray.getJSONObject(i);
                mAdapter.add(new Message(message));
              }
            } catch (Exception error) {
              Log.e("LC", error.toString());
            }
            mAdapter.notifyDataSetChanged();
          }
        };
    task.execute();
  }
コード例 #11
0
  private void asyncDeleteAlarm(final Alarm alarm) {
    final AsyncTask<Alarm, Void, Void> deleteTask =
        new AsyncTask<Alarm, Void, Void>() {

          @Override
          protected Void doInBackground(Alarm... alarms) {
            for (final Alarm alarm : alarms) {
              Alarms.deleteAlarm(AlarmClock.this, alarm.id);
            }
            return null;
          }
        };
    mDeletedAlarm = alarm;
    mUndoShowing = true;
    deleteTask.execute(alarm);
    mUndoBar.show(
        new ActionableToastBar.ActionClickedListener() {
          @Override
          public void onActionClicked() {
            asyncAddAlarm(alarm, false);
            mDeletedAlarm = null;
            mUndoShowing = false;
          }
        },
        0,
        getResources().getString(R.string.alarm_deleted),
        true,
        R.string.alarm_undo,
        true);
  }
コード例 #12
0
 public static void executeTask(final AsyncTask<Void, Void, Void> task) {
   if (Build.VERSION.SDK_INT < Constants.HONEYCOMB) {
     task.execute();
   } else {
     executeTaskHoneycomb(task);
   }
 }
コード例 #13
0
ファイル: Notification.java プロジェクト: JCulver/NotePad-2
  /**
   * Starts a background task that removes all notifications associated with the specified tasks.
   */
  public static void removeWithTaskIds(final Context context, final Long... ids) {
    if (ids.length > 0) {
      final AsyncTask<Long, Void, Void> task =
          new AsyncTask<Long, Void, Void>() {
            @Override
            protected Void doInBackground(final Long... ids) {
              String idStrings = "(";
              ArrayList<String> idsToClear = new ArrayList<String>();
              for (Long id : ids) {
                idStrings += id + ",";
                idsToClear.add(Long.toString(id));
              }
              idStrings = idStrings.substring(0, idStrings.length() - 1);
              idStrings += ")";

              final Cursor c =
                  context
                      .getContentResolver()
                      .query(URI, Columns.FIELDS, Columns.TASKID + " IN " + idStrings, null, null);

              while (c.moveToNext()) {
                // Yes dont just call delete in database
                // We have to remove geofences (in delete)
                Notification n = new Notification(c);
                n.delete(context);
              }
              c.close();

              return null;
            }
          };
      task.execute(ids);
    }
  }
コード例 #14
0
  public void onClick(View view) {
    Log.e("sangwok.onclick", "");
    AsyncTask<String, Void, String> task =
        new AsyncTask<String, Void, String>() {

          @Override
          protected String doInBackground(String... params) {
            String buf = "";
            for (int i = 0; i < params.length; i++) {
              buf += doReq(params[i]);
              Log.e("SANGWOOK", buf);
            }
            return buf;
          }

          @Override
          protected void onPostExecute(String result) {
            //				Pattern p = Pattern.compile("<em class=\"curPrice");
            //				Matcher m = k
            // 여기서 패턴 매칭해서. 다음 주가 가져와서.
            // Textview 의 텍스트를 바꾸는 작업이 있음

            Log.e("SANGWOOK-onPostExecute", result);
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            super.onPostExecute(result);
          }
        };
    task.execute("http://stock.daum.net/item/main.daum?code=035720");
  }
コード例 #15
0
    void downloadFile(final ImageView imageview, String fileUrl) {
      AsyncTask<String, Object, String> task =
          new AsyncTask<String, Object, String>() {
            @Override
            protected String doInBackground(String... params) {
              URL myFileUrl = null;
              try {
                myFileUrl = new URL(params[0]);
              } catch (MalformedURLException e) {
                e.printStackTrace();
              }
              try {
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                bmImg = BitmapFactory.decodeStream(is);
              } catch (IOException e) {
                e.printStackTrace();
              }
              return null;
            }

            @Override
            protected void onPreExecute() {}

            protected void onPostExecute(String unused) {

              imageview.setImageBitmap(bmImg);
            }
          };
      task.execute(fileUrl);
    }
コード例 #16
0
ファイル: ZenModePanel.java プロジェクト: BvbKoala/SourceCode
 /** Start or stop requesting relevant zen mode exit conditions */
 private void setRequestingConditions(final boolean requesting) {
   if (mRequestingConditions == requesting) return;
   if (DEBUG) Log.d(mTag, "setRequestingConditions " + requesting);
   mRequestingConditions = requesting;
   if (mController != null) {
     AsyncTask.execute(
         new Runnable() {
           @Override
           public void run() {
             mController.requestConditions(requesting);
           }
         });
   }
   if (mRequestingConditions) {
     mTimeCondition = parseExistingTimeCondition(mExitCondition);
     if (mTimeCondition != null) {
       mBucketIndex = -1;
     } else {
       mBucketIndex = DEFAULT_BUCKET_INDEX;
       mTimeCondition =
           ZenModeConfig.toTimeCondition(
               mContext, MINUTE_BUCKETS[mBucketIndex], ActivityManager.getCurrentUser());
     }
     if (DEBUG) Log.d(mTag, "Initial bucket index: " + mBucketIndex);
     mConditions = null; // reset conditions
     handleUpdateConditions();
   } else {
     hideAllConditions();
   }
 }
コード例 #17
0
ファイル: AsyncHelper.java プロジェクト: janls/worktime
 public static void start(AsyncTask task) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[] {});
   } else {
     task.execute(new Void[] {});
   }
 }
コード例 #18
0
 /**
  * Run an ASync task on the corresponding executor
  *
  * @param task
  * @return
  */
 private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
   } else {
     return task.execute();
   }
 }
コード例 #19
0
ファイル: AsyncHelper.java プロジェクト: janls/worktime
 public static void startWithParams(AsyncTask task, Object[] params) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
   } else {
     task.execute(params);
   }
 }
コード例 #20
0
  @SuppressLint("NewApi")
  public DiskLruCache(Context context, String cacheName, long cacheSize) {
    mContext = context;
    mCacheName = cacheName;
    mCacheSize = cacheSize;

    int version;
    PackageManager pm = context.getPackageManager();
    try {
      PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
      version = pi.versionCode;
    } catch (NameNotFoundException e) {
      version = 1;
    }

    AsyncTask<Integer, Object, Object> task =
        new AsyncTask<Integer, Object, Object>() {
          @Override
          protected Object doInBackground(Integer... params) {
            initDiskCache(params[0]);
            return null;
          }
        };

    if (Build.VERSION.SDK_INT >= 11) {
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, version);
    } else {
      task.execute(version);
    }
  }
コード例 #21
0
ファイル: FacebookUtil.java プロジェクト: RossKim/Sharer
  public static void postMessage(
      final Activity activity, final String message, final PostCompleteRunnable completeTask) {
    AsyncTask<Void, Void, Response> task =
        new AsyncTask<Void, Void, Response>() {

          @Override
          protected Response doInBackground(Void... params) {
            // TODO Auto-generated method stub
            Bundle param = new Bundle();
            param.putString("message", message);
            Request request =
                new Request(Session.getActiveSession(), "/me/feed", param, HttpMethod.POST);
            return request.executeAndWait();
          }

          @Override
          protected void onPostExecute(Response result) {
            // TODO Auto-generated method stub
            PostResponse postResponse = result.getGraphObjectAs(PostResponse.class);

            if (postResponse == null || postResponse.getId() == null) {
              handleError(activity, result.getError(), completeTask);
            } else {
              completeTask.init(
                  activity.getString(R.string.success_post_facebook),
                  true,
                  true,
                  Account.Facebook.getIndex());
            }
            activity.runOnUiThread(completeTask);
          }
        };

    task.execute();
  }
コード例 #22
0
  void sendMessage(final TextView v) {
    String text = v.getText().toString();
    if (text == null || text.equals("")) {
      return;
    }

    AsyncTask<String, Void, Void> messageTask =
        new AsyncTask<String, Void, Void>() {

          @Override
          protected void onPreExecute() {
            super.onPreExecute();
          }

          @Override
          protected Void doInBackground(String... params) {
            if (chatTarget == null) {
              channelProvider.sendChannelMessage(params[0]);
            } else {
              channelProvider.sendUserMessage(params[0], chatTarget);
            }
            return null;
          }

          @Override
          protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            v.setText("");
          }
        };
    messageTask.execute(text);
  }
コード例 #23
0
  public static void runFirstTime(final Context context) {
    // don't do a "real" root access, just look up if "su" is present and has a version!
    // a real check would annoy the user
    AsyncTask<Void, Void, Boolean> checkRoot =
        new AsyncTask<Void, Void, Boolean>() {

          @Override
          protected Boolean doInBackground(Void... params) {
            return Shell.SU.version(true) != null;
          }

          @Override
          protected void onPostExecute(Boolean probablyRoot) {
            super.onPostExecute(probablyRoot);

            // TODO: remove false condition once the install into system
            // process is stable - #294, #346, #347, #348
            if (false && probablyRoot) {
              // looks like we have root, at least su has a version number and is present

              Intent installIntent = new Intent(context, InstallExtensionDialogActivity.class);
              installIntent.setAction(InstallExtensionDialogActivity.ACTION_FIRST_TIME);
              installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

              PendingIntent resultPendingIntent =
                  PendingIntent.getActivity(
                      context, 0, installIntent, PendingIntent.FLAG_UPDATE_CURRENT);

              NotificationCompat.Builder builder =
                  new NotificationCompat.Builder(context)
                      .setContentIntent(resultPendingIntent)
                      .setSmallIcon(R.drawable.ic_stat_notify)
                      .setContentTitle(
                          context.getString(R.string.system_install_first_time_notification))
                      .setContentText(
                          context.getString(
                              R.string.system_install_first_time_notification_message_short))
                      .setDefaults(Notification.DEFAULT_LIGHTS)
                      .setAutoCancel(true)
                      /*
                       * Sets the big view "big text" style and supplies the
                       * text (the user's reminder message) that will be displayed
                       * in the detail area of the expanded notification.
                       * These calls are ignored by the support library for
                       * pre-4.1 devices.
                       */
                      .setStyle(
                          new NotificationCompat.BigTextStyle()
                              .bigText(
                                  context.getString(
                                      R.string.system_install_first_time_notification_message)));

              NotificationManager nm =
                  (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
              nm.notify(42, builder.build());
            }
          }
        };
    checkRoot.execute();
  }
コード例 #24
0
  private void setupBackgroundBitmap(final View rootView) {
    AsyncTask<Void, Void, Bitmap> asyncTask =
        new AsyncTask<Void, Void, Bitmap>() {

          WeakReference<ViewGroup> view;

          @Override
          protected void onPreExecute() {
            view = new WeakReference(rootView);
          }

          @Override
          protected Bitmap doInBackground(Void... params) {
            Bitmap drawable = null;
            try {
              BitmapFactory.Options options = new BitmapFactory.Options();
              options.inScaled = true;
              options.inSampleSize = 5;
              drawable =
                  BitmapFactory.decodeResource(getResources(), R.drawable.bg_app_image, options);
            } catch (OutOfMemoryError error) {
              error.printStackTrace();
            }
            return drawable;
          }

          @Override
          protected void onPostExecute(Bitmap drawable) {
            if (drawable != null) {
              view.get().setBackground(new BitmapDrawable(getResources(), drawable));
            }
          }
        };
    asyncTask.execute();
  }
コード例 #25
0
  private void startPrimitiveRootFinder() {
    if (!NumberHelper.isValidBitNumberInTextView(txtBits)) {
      Toast.makeText(
              getActivity(),
              "Bit count" + ": You have to input a valid number larger than zero!",
              Toast.LENGTH_LONG)
          .show(); // TODO use StringBuilder
      return;
    }

    int bits = Integer.valueOf(txtBits.getText().toString());

    int numberOfRuns;
    try {
      numberOfRuns = Integer.parseInt(txtNumberOfRuns.getText().toString());
      if (numberOfRuns <= 0) {
        throw new IllegalArgumentException();
      }
    } catch (IllegalArgumentException e) { // also catches NumberFormatException
      Toast.makeText(
              getActivity(),
              "Number of runs" + ": You have to input a valid number larger than zero!",
              Toast.LENGTH_LONG)
          .show(); // TODO use StringBuilder
      return;
    }

    closeSoftKeyboard();
    doPostCalculationStartSetup();

    finderTask = new PrimitiveRootLookupTask(this);
    finderTask.execute(new FinderArguments(bits, numberOfRuns));
  }
コード例 #26
0
ファイル: MainActivity.java プロジェクト: teren4m/Lessons
 public void onClickAsyncThread(final View view) {
   AsyncTask a = new CustomAsyncTask();
   Integer i = (Integer) view.getTag();
   if (i == null) i = 1;
   view.setTag(i + 1);
   a.execute("Some", i, "Simple");
 }
コード例 #27
0
ファイル: Settings.java プロジェクト: feel815/LibrarySystem
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      // 환경설정을 통해 학번 가져오기 //
      SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
      String id = pref.getString("id", "");
      String pw = pref.getString("pw", "");

      JSONObject message = new JSONObject();

      try {
        message.put("service", "certification");
        message.put("id", id);
        message.put("pw", pw);
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      AsyncTask<JSONObject, Void, Void> mJunctionBindingAsyncTask =
          new JunctionAsyncTask(Settings.this, actor, "학사정보 인증중입니다.");

      mJunctionBindingAsyncTask.execute(message); // AsyncTask Thread 시작
    }
    return super.onKeyDown(keyCode, event);
  }
コード例 #28
0
  private void launchMonthActivity() {
    Log.d(LOGTAG, "launchMonthActivity");

    showMonthProgressDialog();
    AsyncTask<Integer, Integer, Integer> monthListAsyncTask = new MonthListAsyncTask();
    monthListAsyncTask.execute(1);
  }
コード例 #29
0
ファイル: SettingsFragment.java プロジェクト: JonnyXDA/WGSB
  private void unRegister() {
    mUnregisterTask =
        new AsyncTask<Void, Void, Void>() {
          @Override
          protected Void doInBackground(Void... params) {
            regId = getRegistrationId();
            ServerUtilities.unregister(regId);
            dbhandler.deleteAllRegId();
            gcm = GoogleCloudMessaging.getInstance(mContext);
            try {
              gcm.unregister();
            } catch (IOException e) {
              e.printStackTrace();
            }
            Intent unregisterIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
            unregisterIntent.putExtra(
                "app", PendingIntent.getBroadcast(mContext, 0, new Intent(), 0));
            mContext.startService(unregisterIntent);
            return null;
          }

          @Override
          protected void onPostExecute(Void result) {
            mUnregisterTask = null;
          }
        };
    mUnregisterTask.execute(null, null, null);
  }
コード例 #30
0
  // ツイートする関数 画像ありき
  void tweet(String s) {

    showNotification(
        R.drawable.ic_launcher, getString(R.string.tweet_result), getString(R.string.tweeting), 1);
    AsyncTask<String, Void, Status> task =
        new AsyncTask<String, Void, Status>() {
          @Override
          protected twitter4j.Status doInBackground(String... params) {
            try {
              final StatusUpdate statusUpdate = new StatusUpdate(String.valueOf(params[0]));

              try {
                gpuImage.getBitmapWithFilterApplied();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                gpuImage.getBitmapWithFilterApplied().compress(Bitmap.CompressFormat.PNG, 100, bos);
                InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
                bos.close();

                statusUpdate.media("test", inputStream);
                inputStream.close();
              } catch (NullPointerException ignored) {

              }
              return twitter.updateStatus(statusUpdate);
            } catch (Exception e) {
              e.printStackTrace();
              return null;
            }
          }

          @Override
          protected void onPostExecute(twitter4j.Status status) {
            if (status != null) {
              NotificationManager notificationManager =
                  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.cancel(1);

              Toast.makeText(
                      MainActivity.this, getString(R.string.tweet_success), Toast.LENGTH_SHORT)
                  .show();
              showNotification(
                  R.drawable.ic_launcher,
                  getString(R.string.tweet_result),
                  getString(R.string.tweet_success),
                  1);
            } else {
              Toast.makeText(
                      MainActivity.this, getString(R.string.tweet_failed), Toast.LENGTH_SHORT)
                  .show();
              showNotification(
                  R.drawable.ic_launcher,
                  getString(R.string.tweet_result),
                  getString(R.string.tweet_failed),
                  1);
            }
          }
        };
    task.execute(s);
  }