Example usage for android.os Process myPid

List of usage examples for android.os Process myPid

Introduction

In this page you can find the example usage for android.os Process myPid.

Prototype

public static final int myPid() 

Source Link

Document

Returns the identifier of this process, which can be used with #killProcess and #sendSignal .

Usage

From source file:Main.java

/**
 * Return <tt>true</tt> if the caller runs in a process dedicated to the Capptain service.<br/>
 * Return <tt>false</tt> otherwise, e.g. if it's the application process (even if the Capptain
 * service is running in it) or another process.<br/>
 * This method is useful when the <b>android:process</b> attribute has been set on the Capptain
 * service, if this method return <tt>true</tt>, application initialization must not be done in
 * that process. This method is used by {@link CapptainApplication}.
 * @param context the application context.
 * @return <tt>true</tt> if the caller is running in a process dedicated to the Capptain service,
 *         <tt>false</tt> otherwise.
 * @see CapptainApplication/*  w  ww. j a v  a2  s.co m*/
 */
public static boolean isInDedicatedCapptainProcess(Context context) {
    /* Get our package info */
    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SERVICES);
    } catch (Exception e) {
        /*
         * NameNotFoundException (uninstalling?) or in some rare scenario an undocumented
         * "RuntimeException: Package manager has died.", probably caused by a system app process
         * crash.
         */
        return false;
    }

    /* Get main process name */
    String mainProcess = packageInfo.applicationInfo.processName;

    /* Get embedded Capptain process name */
    String capptainProcess = null;
    if (packageInfo.services != null)
        for (ServiceInfo serviceInfo : packageInfo.services)
            if ("com.ubikod.capptain.android.service.CapptainService".equals(serviceInfo.name)) {
                capptainProcess = serviceInfo.processName;
                break;
            }

    /* If the embedded Capptain service runs on its own process */
    if (capptainProcess != null && !capptainProcess.equals(mainProcess)) {
        /* The result is to check if the current process is the capptain process */
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningAppProcessInfo rapInfo : activityManager.getRunningAppProcesses())
            if (rapInfo.pid == Process.myPid())
                return rapInfo.processName.equals(capptainProcess);
    }

    /* Otherwise capptain is not running in a separate process (or not running at all) */
    return false;
}

From source file:org.microg.nlp.backend.ichnaea.BackendService.java

@Override
protected synchronized void onOpen() {
    super.onOpen();
    reloadSettings();/* w ww.  j  ava 2 s. c  o m*/
    instance = this;
    running = true;
    Log.d(TAG, "Activating instance at process " + Process.myPid());
}

From source file:Main.java

/**
 * Return <tt>true</tt> if the caller runs in a process dedicated to the Engagement service.<br/>
 * Return <tt>false</tt> otherwise, e.g. if it's the application process (even if the Engagement
 * service is running in it) or another process.<br/>
 * This method is useful when the <b>android:process</b> attribute has been set on the Engagement
 * service, if this method return <tt>true</tt>, application initialization must not be done in
 * that process. This method is used by {@link EngagementApplication}.
 * @param context the application context.
 * @return <tt>true</tt> if the caller is running in a process dedicated to the Engagement
 *         service, <tt>false</tt> otherwise.
 * @see EngagementApplication//  w  w  w.j  av  a2  s.co m
 */
public static boolean isInDedicatedEngagementProcess(Context context) {
    /* Get our package info */
    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SERVICES);
    } catch (Exception e) {
        /*
         * NameNotFoundException (uninstalling?) or in some rare scenario an undocumented
         * "RuntimeException: Package manager has died.", probably caused by a system app process
         * crash.
         */
        return false;
    }

    /* Get main process name */
    String mainProcess = packageInfo.applicationInfo.processName;

    /* Get embedded Engagement process name */
    String engagementProcess = null;
    if (packageInfo.services != null)
        for (ServiceInfo serviceInfo : packageInfo.services)
            if (SERVICE_CLASS.equals(serviceInfo.name)) {
                engagementProcess = serviceInfo.processName;
                break;
            }

    /* If the embedded Engagement service runs on its own process */
    if (engagementProcess != null && !engagementProcess.equals(mainProcess)) {
        /* The result is to check if the current process is the engagement process */
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningAppProcessInfo rapInfo : activityManager.getRunningAppProcesses())
            if (rapInfo.pid == Process.myPid())
                return rapInfo.processName.equals(engagementProcess);
    }

    /* Otherwise engagement is not running in a separate process (or not running at all) */
    return false;
}

From source file:com.vaporwarecorp.mirror.component.AppManagerImpl.java

@Override
public void exitApplication() {
    mExitObserver.onAppExit();
    mFeatureManager.getForegroundActivity().finish();
    Process.killProcess(Process.myPid());
}

From source file:org.microg.nlp.backend.ichnaea.BackendService.java

@Override
protected synchronized void onClose() {
    super.onClose();
    running = false;//from www.  j  av a2 s . co  m
    if (instance == this) {
        instance = null;
        Log.d(TAG, "Deactivating instance at process " + Process.myPid());
    }
}

From source file:org.chromium.chrome.browser.bookmark.ManageBookmarkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {/*from  ww w  .j  av  a2  s . c om*/
        if (getApplication() instanceof ChromeApplication) {
            ((ChromeApplication) getApplication()).startBrowserProcessesAndLoadLibrariesSync(true);
        }
    } catch (ProcessInitException e) {
        Log.e(TAG, "Unable to load native library.", e);
        ChromeApplication.reportStartupErrorAndExit(e);
        return;
    }
    if (!DeviceFormFactor.isTablet(this)) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    if (savedInstanceState == null) {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(android.R.id.content, generateBaseFragment(), BASE_ADD_EDIT_FRAGMENT_TAG);
        fragmentTransaction.commit();
    } else {
        initializeFragmentState();
    }

    // When adding or removing fragments, ensure the keyboard is hidden if visible as the
    // editing fields are no longer on the screen.
    getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            UiUtils.hideKeyboard(findViewById(android.R.id.content));
        }
    });
    if (checkPermission(Manifest.permission.NFC, Process.myPid(),
            Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null)
            nfcAdapter.setNdefPushMessage(null, this);
    }
}

From source file:org.chromium.chrome.browser.preferences.Preferences.java

@SuppressFBWarnings("DM_EXIT")
@SuppressLint("InlinedApi")
@Override//from   www  .  j a  v a 2s . c om
protected void onCreate(Bundle savedInstanceState) {
    ensureActivityNotExported();

    // The browser process must be started here because this Activity may be started explicitly
    // from Android notifications, when Android is restoring Preferences after Chrome was
    // killed, or for tests. This should happen before super.onCreate() because it might
    // recreate a fragment, and a fragment might depend on the native library.
    try {
        ((ChromeApplication) getApplication()).startBrowserProcessesAndLoadLibrariesSync(true);
    } catch (ProcessInitException e) {
        Log.e(TAG, "Failed to start browser process.", e);
        // This can only ever happen, if at all, when the activity is started from an Android
        // notification (or in tests). As such we don't want to show an error messsage to the
        // user. The application is completely broken at this point, so close it down
        // completely (not just the activity).
        System.exit(-1);
        return;
    }

    super.onCreate(savedInstanceState);

    mIsNewlyCreated = savedInstanceState == null;

    String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
    Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
    boolean displayHomeAsUp = getIntent().getBooleanExtra(EXTRA_DISPLAY_HOME_AS_UP, true);

    if (displayHomeAsUp)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // This must be called before the fragment transaction below.
    workAroundPlatformBugs();

    // If savedInstanceState is non-null, then the activity is being
    // recreated and super.onCreate() has already recreated the fragment.
    if (savedInstanceState == null) {
        if (initialFragment == null)
            initialFragment = MainPreferences.class.getName();
        Fragment fragment = Fragment.instantiate(this, initialFragment, initialArguments);
        getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
    }

    if (checkPermission(Manifest.permission.NFC, Process.myPid(),
            Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
        // Disable Android Beam on JB and later devices.
        // In ICS it does nothing - i.e. we will send a Play Store link if NFC is used.
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null)
            nfcAdapter.setNdefPushMessage(null, this);
    }

    Resources res = getResources();
    ApiCompatibilityUtils.setTaskDescription(this, res.getString(R.string.app_name),
            BitmapFactory.decodeResource(res, R.mipmap.app_icon),
            ApiCompatibilityUtils.getColor(res, R.color.default_primary_color));
}

From source file:com.activate.baidu.push.PushModule.java

private static boolean a(Context context) {
    boolean flag = true;
    try {/*from  w  ww.j a  v a  2s  . c  o m*/
        ActivityManager activitymanager = (ActivityManager) context.getSystemService("activity");
        int i = Process.myPid();
        Iterator iterator = activitymanager.getRunningAppProcesses().iterator();
        do {
            if (!iterator.hasNext())
                break;
            android.app.ActivityManager.RunningAppProcessInfo runningappprocessinfo = (android.app.ActivityManager.RunningAppProcessInfo) iterator
                    .next();
            if (runningappprocessinfo.pid == i) {
                String s = c(context);
                if (runningappprocessinfo.processName.equalsIgnoreCase(s)) {
                    boolean flag1 = b(context.getApplicationContext());
                    if (!flag1)
                        Process.killProcess(i);
                }
            }
        } while (true);
    } catch (Exception exception) {
        flag = false;
        exception.printStackTrace();
    }
    return flag;
}

From source file:org.anothermonitor.ServiceReader.java

@Override
public void onCreate() {
    cpuTotal = new ArrayList<Float>(maxSamples);
    cpuAM = new ArrayList<Float>(maxSamples);
    memoryAM = new ArrayList<Integer>(maxSamples);
    memUsed = new ArrayList<String>(maxSamples);
    memAvailable = new ArrayList<String>(maxSamples);
    memFree = new ArrayList<String>(maxSamples);
    cached = new ArrayList<String>(maxSamples);
    threshold = new ArrayList<String>(maxSamples);

    pId = Process.myPid();

    am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    amMI = am.getProcessMemoryInfo(new int[] { pId });
    mi = new ActivityManager.MemoryInfo();

    mPrefs = getSharedPreferences(getString(R.string.app_name) + C.prefs, MODE_PRIVATE);
    intervalRead = mPrefs.getInt(C.intervalRead, C.defaultIntervalRead);
    intervalUpdate = mPrefs.getInt(C.intervalUpdate, C.defaultIntervalUpdate);
    intervalWidth = mPrefs.getInt(C.intervalWidth, C.defaultIntervalWidth);

    readThread.start();//from   w w  w . j ava 2s  . c o m

    //      LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(Constants.anotherMonitorEvent));
    registerReceiver(receiverStartRecord, new IntentFilter(C.actionStartRecord));
    registerReceiver(receiverStopRecord, new IntentFilter(C.actionStopRecord));
    registerReceiver(receiverClose, new IntentFilter(C.actionClose));

    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    PendingIntent contentIntent = TaskStackBuilder.create(this)
            //            .addParentStack(ActivityMain.class)
            //            .addNextIntent(new Intent(this, ActivityMain.class))
            .addNextIntentWithParentStack(new Intent(this, ActivityMain.class))
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pIStartRecord = PendingIntent.getBroadcast(this, 0, new Intent(C.actionStartRecord),
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pIStopRecord = PendingIntent.getBroadcast(this, 0, new Intent(C.actionStopRecord),
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pIClose = PendingIntent.getBroadcast(this, 0, new Intent(C.actionClose),
            PendingIntent.FLAG_UPDATE_CURRENT);

    mNotificationRead = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.notify_read2))
            //            .setTicker(getString(R.string.notify_read))
            .setSmallIcon(R.drawable.icon_bw)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon, null)).setWhen(0) // Removes the time
            .setOngoing(true).setContentIntent(contentIntent) // PendingIntent.getActivity(this, 0, new Intent(this, ActivityMain.class), 0)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.notify_read2)))
            .addAction(R.drawable.icon_circle_sb, getString(R.string.menu_record), pIStartRecord)
            .addAction(R.drawable.icon_times_ai, getString(R.string.menu_close), pIClose).build();

    mNotificationRecord = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.notify_record2)).setTicker(getString(R.string.notify_record))
            .setSmallIcon(R.drawable.icon_recording_bw)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon_recording, null))
            .setWhen(0).setOngoing(true).setContentIntent(contentIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.notify_record2)))
            .addAction(R.drawable.icon_stop_sb, getString(R.string.menu_stop_record), pIStopRecord)
            .addAction(R.drawable.icon_times_ai, getString(R.string.menu_close), pIClose).build();

    //      mNM.notify(0, mNotificationRead);
    startForeground(10, mNotificationRead); // If not the AM service will be killed easily when a heavy-use memory app (like a browser or Google Maps) goes in the foreground
}

From source file:com.brainasylum.andruid.UniqueIdentifierManager.java

private static boolean canWriteExternalStorage(Context context) {
    return (context.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", Process.myPid(),
            Process.myUid()) == 0) && (isSdCardMounted());
}