Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

In this page you can find the example usage for java.util Timer schedule.

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:org.wso2.emm.system.service.EMMSystemService.java

/**
 * Upgrading device firmware over the air (OTA).
 *//*from  w w w.java  2 s  . c  om*/
public void upgradeFirmware(final boolean isStatusCheck) {
    Log.i(TAG, "An upgrade has been requested");

    Preference.putBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress),
            isStatusCheck);
    Preference.putString(context, context.getResources().getString(R.string.firmware_download_progress),
            String.valueOf(DEFAULT_STATE_INFO_CODE));
    Preference.putInt(context, context.getResources().getString(R.string.operation_id), operationId);

    String schedule = null;
    String server;
    if (command != null && !command.trim().isEmpty()) {
        try {
            JSONObject upgradeData = new JSONObject(command);
            if (!upgradeData.isNull(context.getResources().getString(R.string.alarm_schedule))) {
                schedule = (String) upgradeData.get(context.getResources().getString(R.string.alarm_schedule));
            }

            boolean isAutomaticRetry = (Preference.hasPreferenceKey(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                    && Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry)))
                    || !Preference.hasPreferenceKey(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry));
            if (!upgradeData
                    .isNull(context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                isAutomaticRetry = upgradeData.getBoolean(
                        context.getResources().getString(R.string.firmware_upgrade_automatic_retry));
                if (!isAutomaticRetry) {
                    Log.i(TAG, "Automatic retry on firmware upgrade failure is disabled.");
                }
            }

            Preference.putBoolean(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                    isAutomaticRetry);

            if (!upgradeData.isNull(context.getResources().getString(R.string.firmware_server))) {
                server = (String) upgradeData.get(context.getResources().getString(R.string.firmware_server));
                // When the server is empty, that means it is indicating to download from default server
                if (!server.isEmpty() && !Patterns.WEB_URL.matcher(server).matches()) {
                    String message = "Firmware upgrade URL provided is not valid.";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.MALFORMED_OTA_URL, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return;
                } else {
                    Preference.putString(context, context.getResources().getString(R.string.firmware_server),
                            server);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Firmware upgrade payload parsing failed." + e);
            return;
        }
    }
    if (schedule != null && !schedule.trim().isEmpty()) {
        Log.i(TAG, "Upgrade scheduled received: " + schedule);
        Preference.putString(context, context.getResources().getString(R.string.alarm_schedule), schedule);
        try {
            AlarmUtils.setOneTimeAlarm(context, schedule, Constants.Operation.UPGRADE_FIRMWARE, null);
        } catch (ParseException e) {
            CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                    Constants.Status.MALFORMED_REQUEST, e.getMessage());
        }
    } else {
        if (isStatusCheck) {
            Log.i(TAG, "Firmware status check is initiated by admin.");
        } else {
            Log.i(TAG, "Upgrade request initiated by admin.");

            String status = Preference.getString(context,
                    context.getResources().getString(R.string.upgrade_download_status));
            boolean isAutomaticUpgrade = Preference.getBoolean(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry));

            if (Constants.Status.WIFI_OFF.equals(status) && isAutomaticUpgrade && !checkNetworkOnline()) {
                String msg = "Ignoring request as service waiting for WiFi to start upgrade.";
                Log.d(TAG, msg);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING,
                        Constants.Status.OTA_UPGRADE_PENDING, msg);
                return;
            } else if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                String msg = "Checking for existing download. Will proceed this request if current download is no longer ongoing.";
                Log.d(TAG, msg);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING,
                        Constants.Status.OTA_UPGRADE_ONGOING, msg);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.REQUEST_PLACED);
                Timer timeoutTimer = new Timer();
                timeoutTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                                context.getResources().getString(R.string.upgrade_download_status)))) {
                            Log.d(TAG,
                                    "Download is no longer ongoing. Proceeding download request from the agent.");
                            OTADownload otaDownload = new OTADownload(context);
                            otaDownload.startOTA();
                        } else {
                            String msg = "Request ignored because another download is ongoing.";
                            Log.d(TAG, msg);
                            CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                    Constants.Code.FAILURE, Constants.Status.OTA_UPGRADE_ONGOING, msg);
                        }
                    }
                }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                return;
            }
        }

        //Prepare for upgrade
        OTADownload otaDownload = new OTADownload(context);
        otaDownload.startOTA();
    }
}

From source file:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.java

private void cropWallpaper(String wallUrl) {
    if (dialogApply != null) {
        dialogApply.dismiss();//from   w  w w. j a  va2s .co m
    }

    final WallpaperToCrop[] cropTask = new WallpaperToCrop[1];

    final boolean[] enteredCropTask = { false };

    dialogApply = new MaterialDialog.Builder(this).content(R.string.downloading_wallpaper).progress(true, 0)
            .cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (cropTask[0] != null) {
                        cropTask[0].cancel(true);
                    }
                    dialogApply.dismiss();
                    reshowFab(fab);
                    setupFullScreen();
                }
            }).show();

    Glide.with(this).load(wallUrl).asBitmap().dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(final Bitmap resource,
                        GlideAnimation<? super Bitmap> glideAnimation) {
                    if (resource != null && dialogApply.isShowing()) {
                        enteredCropTask[0] = true;
                        if (dialogApply != null) {
                            dialogApply.dismiss();
                        }
                        dialogApply = new MaterialDialog.Builder(AltWallpaperViewerActivity.this)
                                .content(getString(R.string.preparing_wallpaper)).progress(true, 0)
                                .cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog,
                                            @NonNull DialogAction which) {
                                        if (cropTask[0] != null) {
                                            cropTask[0].cancel(true);
                                        }
                                        dialogApply.dismiss();
                                        reshowFab(fab);
                                        setupFullScreen();
                                    }
                                }).show();
                        if (fabOpened) {
                            closeMenu();
                            fabOpened = false;
                        }
                        hideFab(fab);
                        cropTask[0] = new WallpaperToCrop(AltWallpaperViewerActivity.this, dialogApply,
                                resource, layout, item.getWallName());
                        cropTask[0].execute();
                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                runOnUIThread(AltWallpaperViewerActivity.this, new Runnable() {
                                    @Override
                                    public void run() {
                                        String content = getString(R.string.preparing_wallpaper) + "\n"
                                                + getString(R.string.download_takes_longer);

                                        dialogApply.setContent(content);
                                        dialogApply.setActionButton(DialogAction.POSITIVE,
                                                android.R.string.cancel);
                                    }
                                });
                            }
                        }, 7000);
                    }
                }
            });

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUIThread(AltWallpaperViewerActivity.this, new Runnable() {
                @Override
                public void run() {
                    if (!enteredCropTask[0]) {
                        String newContent = getString(R.string.downloading_wallpaper) + "\n"
                                + getString(R.string.download_takes_longer);
                        dialogApply.setContent(newContent);
                        dialogApply.setActionButton(DialogAction.POSITIVE, android.R.string.cancel);
                    }
                }
            });
        }
    }, 10000);
}

From source file:org.wso2.iot.system.service.SystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    String AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();//from  w w  w.  j  a  v  a 2s . c o  m
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "IoT agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = !Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                || Preference.getBoolean(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:lvge.com.myapp.modules.shop_management.NotAuthenticationFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();

    view = inflater.inflate(R.layout.fragment_shop_manage_not_authentication, container, false);
    ctx = getActivity();/*from  w w  w  .java  2  s . co m*/
    img_business_licence = (ImageView) view.findViewById(R.id.img_business_licence);
    img_business_licence.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            id_iamge = R.id.img_business_licence;
            show(v);
        }
    });

    img_identity_card_positive = (ImageView) view.findViewById(R.id.img_identity_card_positive);
    img_identity_card_positive.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            id_iamge = R.id.img_identity_card_positive;
            show(v);
        }
    });

    img_identity_card_negative = (ImageView) view.findViewById(R.id.img_identity_card_negative);
    img_identity_card_negative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            id_iamge = R.id.img_identity_card_negative;
            show(v);
        }
    });

    shop_authentication_company_name = (EditText) view.findViewById(R.id.shop_authentication_company_name);

    TextView shop_authentication_confirm_and_submit = (TextView) view
            .findViewById(R.id.shop_authentication_confirm_and_submit);
    shop_authentication_confirm_and_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //                HasCommitAuthenticationFragment HasCommit = new HasCommitAuthenticationFragment();
            //                FragmentTransaction transaction =getFragmentManager().beginTransaction();
            //                transaction.replace(R.id.fragment_container_authentication,HasCommit);
            //                transaction.commit();

            L.d("shop_authentication_confirm_and_submit is clicked");
            if (shop_authentication_company_name.getText().toString().isEmpty()) {
                L.d("company_name is null");
                Toast.makeText(ctx, "???", Toast.LENGTH_SHORT).show();
                return;
            }

            //                if (img_business_licence_bool || img_identity_card_positive_bool || img_identity_card_negative_bool)
            //                    startProgerssDialog();
            //                else {
            //                    Toast.makeText(ctx, "", Toast.LENGTH_SHORT).show();
            //                    return;
            //                }

            try {
                if (img_business_licence_bool) {
                    final List<String> filePaths = new ArrayList<>();
                    final Map<String, Object> map = new HashMap<String, Object>();
                    img_business_licence.setDrawingCacheEnabled(true);
                    img_business_licence_bitmap = img_business_licence.getDrawingCache();
                    filePaths.add(saveBitmap("1", img_business_licence_bitmap));

                    new Thread() {
                        public void run() {
                            try {
                                // showProgressDialog();
                                if (img_business_licence.getTag() == null)
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_BUSINESS_LICENSE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY, "");
                                else
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_BUSINESS_LICENSE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY,
                                            img_business_licence.getTag().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    Thread.sleep(1000);
                    img_business_licence_bool = false;
                }
                if (img_identity_card_positive_bool) {
                    final List<String> filePaths = new ArrayList<>();
                    final Map<String, Object> map = new HashMap<String, Object>();
                    img_identity_card_positive.setDrawingCacheEnabled(true);
                    img_identity_card_positive_bitmap = img_identity_card_positive.getDrawingCache();
                    filePaths.add(saveBitmap("2", img_identity_card_positive_bitmap));

                    new Thread() {
                        public void run() {
                            try {
                                // showProgressDialog();
                                if (img_identity_card_positive.getTag() == null)
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_IDENTITY_CARD_POSITIVE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY, "");
                                else
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_IDENTITY_CARD_POSITIVE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY,
                                            img_identity_card_positive.getTag().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    Thread.sleep(1000);
                    img_identity_card_positive_bool = false;
                }
                if (img_identity_card_negative_bool) {
                    final List<String> filePaths = new ArrayList<>();
                    final Map<String, Object> map = new HashMap<String, Object>();
                    img_identity_card_negative.setDrawingCacheEnabled(true);
                    img_identity_card_negative_bitmap = img_identity_card_negative.getDrawingCache();
                    filePaths.add(saveBitmap("3", img_identity_card_negative_bitmap));

                    new Thread() {
                        public void run() {
                            try {
                                // showProgressDialog();
                                if (img_identity_card_negative.getTag() == null)
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_IDENTITY_CARD_NEGATIVE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY, "");
                                else
                                    post_str(filePaths, ShopManagementParameter.SHOPIMG_IDENTITY_CARD_NEGATIVE,
                                            ShopManagementParameter.SHOPIMG_IDENTITY,
                                            img_identity_card_negative.getTag().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    Thread.sleep(1000);
                    img_identity_card_negative_bool = false;
                }
            } catch (Exception e) {
                stopProgressDialog();
                Toast.makeText(ctx, "?", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            try {
                startProgerssDialog();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        OkHttpUtils.post()
                                //get 
                                .url("http://www.lvgew.com/obdcarmarket/sellerapp/seller/sellerIdentifycationApply") //?
                                .addParams("companyName", shop_authentication_company_name.getText().toString())
                                .build().execute(new Callback() {

                                    @Override
                                    public Object parseNetworkResponse(Response response, int i)
                                            throws Exception {
                                        String string = response.body().string();//?Json?
                                        //json?
                                        //LoginResultModel??
                                        L.d(string);
                                        result1 = new Gson().fromJson(string, CustomerDetail.class);

                                        return result1;
                                    }

                                    @Override
                                    public void onError(Call call, Exception e, int i) {
                                        stopProgressDialog();
                                    }

                                    @Override
                                    public void onResponse(Object o, int i) {
                                        if (null != o) {
                                            result1 = (CustomerDetail) o;
                                            L.d(String.valueOf(result1.getOperationResult().getResultCode()));
                                            if (result1.getOperationResult().getResultCode() == 0) {
                                                Toast.makeText(ctx, "????",
                                                        Toast.LENGTH_SHORT).show();
                                                mHandler.sendEmptyMessage(1002);
                                            } else {
                                                Toast.makeText(ctx, result1.getOperationResult().getResultMsg(),
                                                        Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                        stopProgressDialog();
                                    }
                                });
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task, 2000);//3?
            } catch (Exception e) {
                stopProgressDialog();
                Toast.makeText(ctx, "?", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    });

    network_init(view);
    return view;
}

From source file:org.wso2.emm.system.service.EMMSystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();//  w  ww  .j  a va2 s . c om
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "EMM agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = (Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                && Preference.getBoolean(context,
                                        context.getResources()
                                                .getString(R.string.firmware_upgrade_automatic_retry)))
                                || !Preference.hasPreferenceKey(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.java

private void showApplyWallpaperDialog(final Activity context, final String wallUrl) {
    ISDialogs.showApplyWallpaperDialog(this, new MaterialDialog.SingleButtonCallback() {
        @Override/*from   w  ww .  j  ava 2s .  co  m*/
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            if (dialogApply != null) {
                dialogApply.dismiss();
            }

            if (fabOpened) {
                closeMenu();
                fabOpened = false;
            }

            hideFab(fab);

            final ApplyWallpaper[] applyTask = new ApplyWallpaper[1];

            final boolean[] enteredApplyTask = { false };

            dialogApply = new MaterialDialog.Builder(AltWallpaperViewerActivity.this)
                    .content(R.string.downloading_wallpaper).progress(true, 0).cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (applyTask[0] != null) {
                                applyTask[0].cancel(true);
                            }
                            dialogApply.dismiss();
                            reshowFab(fab);
                            setupFullScreen();
                        }
                    }).show();

            Glide.with(context).load(wallUrl).asBitmap().dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(final Bitmap resource,
                                GlideAnimation<? super Bitmap> glideAnimation) {
                            if (resource != null && dialogApply.isShowing()) {
                                enteredApplyTask[0] = true;

                                if (dialogApply != null) {
                                    dialogApply.dismiss();
                                }

                                dialogApply = new MaterialDialog.Builder(context)
                                        .content(R.string.setting_wall_title).progress(true, 0)
                                        .cancelable(false).show();

                                applyTask[0] = new ApplyWallpaper(context, resource,
                                        new ApplyWallpaper.ApplyCallback() {
                                            @Override
                                            public void afterApplied() {
                                                runOnUIThread(context, new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (dialogApply != null) {
                                                            dialogApply.dismiss();
                                                        }
                                                        dialogApply = new MaterialDialog.Builder(context)
                                                                .content(R.string.set_as_wall_done)
                                                                .positiveText(android.R.string.ok).show();

                                                        dialogApply.setOnDismissListener(
                                                                new DialogInterface.OnDismissListener() {
                                                                    @Override
                                                                    public void onDismiss(
                                                                            DialogInterface dialogInterface) {
                                                                        reshowFab(fab);
                                                                        setupFullScreen();
                                                                    }
                                                                });
                                                    }
                                                });
                                            }
                                        });
                                applyTask[0].execute();
                            }
                        }
                    });

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUIThread(AltWallpaperViewerActivity.this, new Runnable() {
                        @Override
                        public void run() {
                            if (!enteredApplyTask[0]) {
                                String newContent = context.getString(R.string.downloading_wallpaper) + "\n"
                                        + context.getString(R.string.download_takes_longer);
                                dialogApply.setContent(newContent);
                                dialogApply.setActionButton(DialogAction.POSITIVE, android.R.string.cancel);
                            }
                        }
                    });
                }
            }, 10000);
        }
    }, new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            if (!PermissionUtils.canAccessStorage(AltWallpaperViewerActivity.this)) {
                PermissionUtils.setViewerActivityAction("crop");
                PermissionUtils.requestStoragePermission(AltWallpaperViewerActivity.this);
            } else {
                cropWallpaper(wallUrl);
            }
        }
    }, new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            reshowFab(fab);
            setupFullScreen();
        }
    });
}

From source file:org.apache.slider.common.tools.SliderUtils.java

/**
 * trigger a  JVM halt with no clean shutdown at all
 * @param status status code for exit/*from  ww w. j a va 2  s  .  c om*/
 * @param text text message
 * @param delay delay in millis
 * @return the timer (assuming the JVM hasn't halted yet)
 *
 */
public static Timer haltAM(int status, String text, int delay) {

    Timer timer = new Timer("halt timer", false);
    timer.schedule(new DelayedHalt(status, text), delay);
    return timer;
}

From source file:org.hubiquitus.android.SimpleClient.SimpleClientActivity.java

@Override
public void onMessage(final HMessage message) {
    runOnUiThread(new Runnable() {
        public void run() {
            outputTextArea.append("HMessage : " + message + "\n\n");
            Timer scrollTimer = new Timer();
            TimerTask scrollTask = new TimerTask() {

                @Override// w  ww . j av a2 s  .  com
                public void run() {
                    runOnUiThread(new Runnable() {

                        public void run() {
                            outputScroller.smoothScrollTo(0, outputTextArea.getBottom());

                        }
                    });

                }
            };

            scrollTimer.schedule(scrollTask, 10);
        }
    });

}

From source file:org.hubiquitus.android.SimpleClient.SimpleClientActivity.java

@Override
public void onStatus(final HStatus status) {
    runOnUiThread(new Runnable() {

        public void run() {
            connectionStatusLabel.setText(client.status().toString());
            outputTextArea.append("Status : " + status.getStatus() + " error : " + status.getErrorCode()
                    + "  errorMsg : " + status.getErrorMsg() + "\n\n");
            Timer scrollTimer = new Timer();
            TimerTask scrollTask = new TimerTask() {

                @Override/*ww w.j a v  a  2 s .c o  m*/
                public void run() {
                    runOnUiThread(new Runnable() {

                        public void run() {
                            outputScroller.smoothScrollTo(0, outputTextArea.getBottom());

                        }
                    });

                }
            };

            scrollTimer.schedule(scrollTask, 10);
        }
    });
}

From source file:com.turn.ttorrent.client.Client.java

/**
 * Start the seeding period, if any./*from   w  ww . j  a v  a2 s .  co m*/
 *
 * <p>
 * This method is called when all the pieces of our torrent have been
 * retrieved. This may happen immediately after the client starts if the
 * torrent was already fully download or we are the initial seeder client.
 * </p>
 *
 * <p>
 * When the download is complete, the client switches to seeding mode for
 * as long as requested in the <code>share()</code> call, if seeding was
 * requested. If not, the {@link ClientShutdown} will execute
 * immediately to stop the client's main loop.
 * </p>
 *
 * @see ClientShutdown
 */
private synchronized void seed() {
    // Silently ignore if we're already seeding.
    if (ClientState.SEEDING.equals(this.getState())) {
        return;
    }

    logger.info("Download of {} pieces completed.", this.torrent.getPieceCount());

    this.setState(ClientState.SEEDING);
    if (this.seed < 0) {
        logger.info("Seeding indefinetely...");
        return;
    }

    // In case seeding for 0 seconds we still need to schedule the task in
    // order to call stop() from different thread to avoid deadlock
    logger.info("Seeding for {} seconds...", this.seed);
    Timer timer = new Timer();
    timer.schedule(new ClientShutdown(this, timer), this.seed * 1000);
}