Example usage for android.app ActivityManager getRunningTasks

List of usage examples for android.app ActivityManager getRunningTasks

Introduction

In this page you can find the example usage for android.app ActivityManager getRunningTasks.

Prototype

@Deprecated
public List<RunningTaskInfo> getRunningTasks(int maxNum) throws SecurityException 

Source Link

Document

Return a list of the tasks that are currently running, with the most recent being first and older ones after in order.

Usage

From source file:com.air.mobilebrowser.ActivityWatchService.java

/**
 * Hide any application that is in the foreground and is not
 * in the white-list, and collapse the status bar.
 *///from w w w . jav a 2  s .c  o  m
private void hideApplications() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);

    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;

        String packageName = topActivity.getPackageName();

        if (!packageName.equals(getPackageName()) && !mApplicationWhitelist.contains(packageName)) {
            //We hide the activity, by bringing the BrowserActivity back in front.
            Intent intent = new Intent(this, BrowserActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            //Visual indicator that we are hiding an app.
            Toast.makeText(this, "Blocked " + packageName, Toast.LENGTH_SHORT).show();
        }
    }

    try {
        final Object service = getSystemService("statusbar");
        Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
            final Method collapse = statusbarManager.getMethod("collapse");
            collapse.setAccessible(true);
            collapse.invoke(service);
        } else {
            final Method collapse = statusbarManager.getMethod("collapsePanels");
            collapse.setAccessible(true);
            collapse.invoke(service);
        }
    } catch (Exception ex) {
        Log.e(TAG, "Failed to collapse status bar");
    }

    List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();

    for (RunningAppProcessInfo info : appList) {
        am.killBackgroundProcesses(info.processName);
    }

    appList = am.getRunningAppProcesses();

    for (RunningAppProcessInfo info : appList) {
        if (mAppBlacklist.contains(info.processName)) {
            Intent intent = new Intent(super.getResources().getString(R.string.intent_black_logtag));
            LocalBroadcastManager.getInstance(super.getApplicationContext()).sendBroadcast(intent);
        }
    }

}

From source file:com.neighbor.ex.tong.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from  ww w  .j a  v  a 2 s .c  o m
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            Log.e("GcmIntentService", "Send error : " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.e("GcmIntentService", "Deleted messages on server : " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            String msg = "";
            String SenderCarNo = "";
            String Userseq = "";

            Iterator<String> iterator = extras.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = extras.get(key).toString();
                try {
                    if (key.equals("MESSAGE"))
                        msg = URLDecoder.decode(value, "utf-8");
                    if (key.equals("SENDER_CAR_NUM"))
                        SenderCarNo = URLDecoder.decode(value, "utf-8");
                    if (key.equals("SENDER_SEQ")) {
                        Userseq = String.valueOf(value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!msg.equalsIgnoreCase("UPDATE_OK") && !msg.equalsIgnoreCase("")) {

                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> services = am.getRunningTasks(Integer.MAX_VALUE);

                boolean isRunning = false;

                if (services.get(0).topActivity.getPackageName().toString()
                        .equalsIgnoreCase(this.getPackageName().toString())) {
                    isRunning = true;
                }

                if (false == isRunning) {
                    Uri path = getSoundPath(msg);
                    NotiMessage(msg, path);
                } else {
                    mHandler.post(new DisplayToast(this, msg));
                }

                //                    Log.d("hts", "sendGCMIntent msg : " + msg + "\t Userseq : " + Userseq + "\t SenderCarNo : " + SenderCarNo);
                sendGCMIntent(GcmIntentService.this, msg, null, SenderCarNo, Userseq);
            }
        }
    }

    GCMBroadCastReceiver.completeWakefulIntent(intent);
}

From source file:org.cgiar.ilri.odk.pull.backend.services.PersistentService.java

/**
 * This method gets all forms from the SQLite database that are due for fetching external data for.
 * Forms include:/*from  w  w w. ja  v  a  2s .co m*/
 *      - Those that need to be refreshed after every X minutes and these X minutes have expired
 *      - Those whose external item sets are to be fetched whenever ODK Collect is launched
 *
 * @return A list of forms whose external item sets are to be fetched
 */
private List<Form> getAllDueForms() {
    List<Form> allForms = DataHandler.getAllForms(this);

    List<Form> dueForms = new ArrayList<Form>();

    //check if the top most activity is ODK Collect
    ActivityManager activityManager = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
    String topMostActivityPackage = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();

    boolean odkTop = false;
    if (topMostActivityPackage.equals(ODK_COLLECT_PACKAGE_NAME)) {
        //check if ODK Collect was already launched the last time this service ran
        String isODKAlreadyLaunched = DataHandler.getSharedPreference(this, DataHandler.PREF_ODK_ALREADY_ON,
                DataHandler.ODK_NOT_LAUCHED);

        if (isODKAlreadyLaunched.equals(DataHandler.ODK_NOT_LAUCHED)) {//means that this service has not seen odk at the top before
            DataHandler.setSharedPreference(this, DataHandler.PREF_ODK_ALREADY_ON,
                    DataHandler.ODK_ALREADY_LAUCHED);
            odkTop = true;
            Log.i(TAG, "ODK Collect now the current activity");
        }
    } else {
        Log.d(TAG, "Current activity is " + topMostActivityPackage);
        DataHandler.setSharedPreference(this, DataHandler.PREF_ODK_ALREADY_ON, DataHandler.ODK_NOT_LAUCHED);
    }

    /*
    For all the fetched forms check if the need updates based on:
    - them needing an update based on the staleness of the data based on the last time the data was updated
    - them needing an update because ODK Collect has been launched
      */
    for (int index = 0; index < allForms.size(); index++) {
        Log.d(TAG, "Current form is: " + allForms.get(index).getName());
        if (allForms.get(index).isTimeForPull() || (odkTop && allForms.get(index).isPullWhenODKLaunched())) {
            dueForms.add(allForms.get(index));
            Log.i(TAG, allForms.get(index).getName() + " needs data pulled like now");
        } else {
            Log.i(TAG, allForms.get(index).getName() + " does not need data pulled right now");
        }
    }

    return dueForms;
}

From source file:de.luhmer.owncloudnewsreader.services.OwnCloudSyncService.java

private void finishedSync() {
    TeslaUnreadManager.PublishUnreadCount(this);
    WidgetProvider.UpdateWidget(this);

    syncRunning = false;/*w  ww .j av a2 s  .co  m*/
    syncStopWatch.stop();
    Log.v(TAG, "Time needed (synchronization): " + syncStopWatch.toString());

    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(OwnCloudSyncService.this);
    int newItemsCount = mPrefs.getInt(Constants.LAST_UPDATE_NEW_ITEMS_COUNT_STRING, 0);
    if (newItemsCount > 0) {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        if (!componentInfo.getPackageName().equals("de.luhmer.owncloudnewsreader")) {
            Resources res = getResources();
            String tickerText = res.getQuantityString(R.plurals.notification_new_items_ticker, newItemsCount,
                    newItemsCount);
            String contentText = res.getQuantityString(R.plurals.notification_new_items_text, newItemsCount,
                    newItemsCount);
            String title = getString(R.string.app_name);

            if (mPrefs.getBoolean(SettingsActivity.CB_SHOW_NOTIFICATION_NEW_ARTICLES_STRING, true))//Default is true
                NotificationManagerNewsReader.getInstance(OwnCloudSyncService.this).ShowMessage(title,
                        tickerText, contentText);
        }
    }

    List<IOwnCloudSyncServiceCallback> callbackList = getCallBackItemsAndBeginBroadcast();
    for (IOwnCloudSyncServiceCallback icb : callbackList) {
        try {
            icb.finishedSync();
            //icb.finishedSyncOfItems();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    callbacks.finishBroadcast();
}

From source file:com.example.product.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from w ww  . j a v a2 s  .  c  o  m
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_SEND_ERROR");
            //do nothing              
            //sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_DELETED");
            //do nothing            
            //sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            //? ?? Notification? .              
            // This loop represents the service doing some work.
            /*
             for (int i = 0; i < 5; i++) {
            Log.i(TAG, "Working... " + (i + 1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
             }
             */

            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            //sendNotification("Received: " + extras.toString());                
            //test sendNotification
            sendNotification(extras);

            Log.i(TAG, "Received: " + extras.toString());

            //??  
            if (!isScreenOn(this)) {

                Log.i(TAG, "screen is off");

                //test
                Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //  .
                this.startActivity(popupIntent);

            }
            //??  
            else {
                ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> runList = am.getRunningTasks(10);
                ComponentName name = runList.get(0).topActivity;
                String className = name.getClassName();
                boolean isAppRunning = false;

                Log.i(TAG, "className ==" + className);
                //? ?? AcitivityPopUp ?
                if (className.equals("com.example.product.ActivityPopUp")) {
                    isAppRunning = true;
                }

                //?? ?
                if (isAppRunning == true) {
                    Log.i(TAG, "screen is off, but popup is on");

                    //test
                    Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //  .
                    this.startActivity(popupIntent);
                    // ? ?  ? 
                }
                //? ? ? 
                else {

                    // ? ? ?  ? 

                }
            }

        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:eu.nerdz.app.messenger.GcmIntentService.java

public boolean isActivityOpen() {
    ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);

    String name = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();

    return ConversationActivity.class.getCanonicalName().equalsIgnoreCase(name)
            || ConversationsListActivity.class.getCanonicalName().equalsIgnoreCase(name);

}

From source file:com.openerp.services.ExpenseSyncService.java

/**
 * Perform sync.//from   w w w .  j av  a  2s .c  o m
 *
 * @param context    the context
 * @param account    the account
 * @param extras     the extras
 * @param authority  the authority
 * @param provider   the provider
 * @param syncResult the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    Log.d(TAG, "ExpenseSyncService->performSync()");
    Intent intent = new Intent();
    Intent updateWidgetIntent = new Intent();
    updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.setAction(SyncFinishReceiver.SYNC_FINISH);
    OEUser user = OpenERPAccountManager.getAccountDetail(context, account.name);
    try {
        ExpenseDBHelper expense_db = new ExpenseDBHelper(context);
        expense_db.setAccountUser(user);
        OEHelper oe = expense_db.getOEInstance();
        if (oe == null) {
            return;
        }
        int user_id = user.getUser_id();

        // Updating User Context for OE-JSON-RPC
        JSONObject newContext = new JSONObject();
        //newContext.put("default_model", "res.users");
        //newContext.put("default_res_id", user_id);

        OEArguments arguments = new OEArguments();
        // Param 1 : domain
        //OEDomain domain = new OEDomain();
        //arguments.add(domain);
        // Param 2 : context
        arguments.add(oe.updateContext(newContext));

        //???
        List<Integer> ids = expense_db.ids();
        if (oe.syncWithMethod("get_waiting_audit_expenses", arguments, true)) {
            int affected_rows = oe.getAffectedRows();
            Log.d(TAG, "ExpenseSyncService[arguments]:" + arguments.toString());
            Log.d(TAG, "ExpenseSyncService->affected_rows:" + affected_rows);
            List<Integer> affected_ids = oe.getAffectedIds();
            boolean notification = true;
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equalsIgnoreCase("com.openerp")) {
                notification = false;
            }
            if (notification && affected_rows > 0) {
                OENotificationHelper mNotification = new OENotificationHelper();
                Intent mainActiivty = new Intent(context, MainActivity.class);
                mainActiivty.setAction("EXPENSES");
                mNotification.setResultIntent(mainActiivty, context);

                String notify_title = context.getResources().getString(R.string.expenses_sync_notify_title);
                notify_title = String.format(notify_title, affected_rows);

                String notify_body = context.getResources().getString(R.string.expenses_sync_notify_body);
                notify_body = String.format(notify_body, affected_rows);

                mNotification.showNotification(context, notify_title, notify_body, authority,
                        R.drawable.ic_oe_notification);
            }
            intent.putIntegerArrayListExtra("new_ids", (ArrayList<Integer>) affected_ids);
        }
        //?expense?
        List<Integer> updated_ids = updateOldExpenses(expense_db, oe, user, ids);

    } catch (Exception e) {
        e.printStackTrace();
    }
    if (user.getAndroidName().equals(account.name)) {
        context.sendBroadcast(intent);
        //context.sendBroadcast(updateWidgetIntent);
    }
}

From source file:com.openerp.services.VoucherSyncService.java

/**
 * Perform sync.//w  ww  .  j a  v  a 2s .c om
 *
 * @param context    the context
 * @param account    the account
 * @param extras     the extras
 * @param authority  the authority
 * @param provider   the provider
 * @param syncResult the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    Log.d(TAG, "VoucherSyncService->performSync()");
    Intent intent = new Intent();
    Intent updateWidgetIntent = new Intent();
    updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.setAction(SyncFinishReceiver.SYNC_FINISH);
    OEUser user = OpenERPAccountManager.getAccountDetail(context, account.name);
    try {
        VoucherDB voucherDb = new VoucherDB(context);
        voucherDb.setAccountUser(user);
        OEHelper oe = voucherDb.getOEInstance();
        if (oe == null) {
            return;
        }
        int user_id = user.getUser_id();

        // Updating User Context for OE-JSON-RPC
        JSONObject newContext = new JSONObject();
        //newContext.put("default_model", "res.users");
        //newContext.put("default_res_id", user_id);

        OEArguments arguments = new OEArguments();
        // Param 1 : domain
        OEDomain domain = new OEDomain();
        //type = payment
        arguments.add(domain);
        // Param 2 : context
        arguments.add(oe.updateContext(newContext));

        //???
        List<Integer> ids = voucherDb.ids();
        if (oe.syncWithMethod("get_waiting_audit_vouchers", arguments, true)) {
            int affected_rows = oe.getAffectedRows();
            Log.d(TAG, "VoucherSyncService[arguments]:" + arguments.toString());
            Log.d(TAG, "VoucherSyncService->affected_rows:" + affected_rows);
            List<Integer> affected_ids = oe.getAffectedIds();
            boolean notification = true;
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equalsIgnoreCase("com.openerp")) {
                notification = false;
            }
            if (notification && affected_rows > 0) {
                OENotificationHelper mNotification = new OENotificationHelper();
                Intent mainActiivty = new Intent(context, MainActivity.class);
                mainActiivty.setAction("VOUCHERS");
                mNotification.setResultIntent(mainActiivty, context);

                String notify_title = context.getResources().getString(R.string.vouchers_sync_notify_title);
                notify_title = String.format(notify_title, affected_rows);

                String notify_body = context.getResources().getString(R.string.vouchers_sync_notify_body);
                notify_body = String.format(notify_body, affected_rows);

                mNotification.showNotification(context, notify_title, notify_body, authority,
                        R.drawable.ic_oe_notification);
            }
            intent.putIntegerArrayListExtra("new_ids", (ArrayList<Integer>) affected_ids);
        }
        //?expense?
        List<Integer> updated_ids = updateOldVouchers(voucherDb, oe, user, ids);

    } catch (Exception e) {
        e.printStackTrace();
    }
    if (user.getAndroidName().equals(account.name)) {
        context.sendBroadcast(intent);
        //context.sendBroadcast(updateWidgetIntent);
    }
}

From source file:fr.inria.ucn.collectors.RunningAppsCollector.java

@SuppressLint("NewApi")
@Override// ww w  .  j  a  v a2 s .c  om
public void run(Context c, long ts) {
    try {
        ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = c.getPackageManager();

        JSONObject data = new JSONObject();

        // running tasks
        JSONArray runTaskArray = new JSONArray();
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(50);
        boolean first = true;
        for (ActivityManager.RunningTaskInfo info : taskInfo) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("task_id", info.id);
            jinfo.put("task_num_activities", info.numActivities);
            jinfo.put("task_num_running", info.numRunning);

            // is this the foreground process ?
            jinfo.put("task_foreground", first);
            if (first) {
                first = false;
            }

            if (info.topActivity != null) {
                jinfo.put("task_top_class_name", info.topActivity.getClassName());
                jinfo.put("task_top_package_name", info.topActivity.getPackageName());
                try {
                    // map package name to app label
                    CharSequence appLabel = pm.getApplicationLabel(pm.getApplicationInfo(
                            info.topActivity.getPackageName(), PackageManager.GET_META_DATA));
                    jinfo.put("task_app_label", appLabel.toString());
                } catch (NameNotFoundException e) {
                }
            }

            runTaskArray.put(jinfo);
        }
        data.put("runningTasks", runTaskArray);

        // processes
        JSONArray runProcArray = new JSONArray();
        for (ActivityManager.RunningAppProcessInfo pinfo : am.getRunningAppProcesses()) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("proc_uid", pinfo.uid);
            jinfo.put("proc_name", pinfo.processName);
            jinfo.put("proc_packages", Helpers.getPackagesForUid(c, pinfo.uid));
            runProcArray.put(jinfo);
        }
        data.put("runningAppProcesses", runProcArray);

        // done
        Helpers.sendResultObj(c, "running_apps", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json obj", jex);
    }
}

From source file:com.arctech.gcm.MyGcmListenerService.java

public boolean checkApp() {
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

    // get the info from the currently running task
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

    //        ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
    //        List<ActivityManager.RunningTaskInfo> services = activityManager
    //                .getRunningTasks(Integer.MAX_VALUE);

    ComponentName componentInfo = taskInfo.get(0).topActivity;
    Log.i("Package Activity", " " + componentInfo.getPackageName());
    Log.i("Class Activity", " " + componentInfo.getClassName());
    if (componentInfo.getClassName().equalsIgnoreCase("com.arctech.stikyhive.StikyChatMoreActivity")) {
        Log.i(TAG, "Chat More Activity");
        StikyChatMoreActivity.flagGCM = true;
        flagNoti = false;/*from www.j  a  va  2  s  . c  o  m*/
        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
        return false;
    } else if (componentInfo.getClassName().equalsIgnoreCase("com.arctech.stikyhive.ChattingActivity")) {
        Log.i("TAG", componentInfo.getClass() + " ");
        Intent registrationComplete = new Intent(QuickstartPreferences.CHAT_REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
        return true;
    } else if (componentInfo.getPackageName() != "com.arctech.stikyhive") {
        flagNoti = true;
        return false;
    } else {
        flagNoti = false;
        return false;
    }
}