Android java process pid

How do I get process ID of a Java application?

The code below show you how to get the process ID of a Java application. We can use the ManagementFactory.getRuntimeMXBean().getName() to get the process ID. In Windows the method return a string in the form of [PID]@[MACHINE_NAME] .

Since JDK 10, we can use ManagementFactory.getRuntimeMXBean().getPid() method to get the process ID. This method returns the process ID representing the running Java virtual machine.

package org.kodejava.lang.management; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; public class GetProcessID < public static void main(String[] args) < RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); // Get name representing the running Java virtual machine. // It returns something like 35656@Krakatau. The value before // the @ symbol is the PID. String jvmName = bean.getName(); System.out.println("Name = " + jvmName); // Extract the PID by splitting the string returned by the // bean.getName() method. long pid = Long.parseLong(jvmName.split("@")[0]); System.out.println("PID = " + pid); // Get the process ID representing the running Java virtual machine. // Since JDK 10. pid = ManagementFactory.getRuntimeMXBean().getPid(); System.out.println("PID language-text">Name = 35656@Krakatau PID = 35656 PID = 35656 

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Читайте также:  What is hashmap and treemap in java

Источник

Find Out the Running Process Id by Package Name

Android — How to get the processName or packageName by using PID?

Hello you can use this code, it works for me in Android 2.3.3:

private String getAppName(int pID)
String processName = "";
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while(i.hasNext())
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
try
<
if(info.pid == pID)
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +" Label: "+c.toString());
//processName = c.toString();
processName = info.processName;
>
>
catch(Exception e)
//Log.d("Process", "Error>> :"+ e.toString());
>
>
return processName;
>

How to get PID from package name?

ActivityManager aM = (ActivityManager);
getApplicationContext().getSystemService(getApplicationContext().ACTIVITY_SERVICE);
aM.restartPackage("com.android.email");

Kill BackGround Process Code

ActivityManager aM = (ActivityManager)
getApplicationContext().getSystemService(Catalogue.content_holder.getApplicationContext().ACTIVITY_SERVICE);
aM.killBackgroundProcesses("com.android.email");

Here is code which fetches all running Application and check wether email app is already running or not , if it is running then kill that process

ActivityManager manager = (ActivityManager) getApplicationContext.getSystemService(getApplicationContext.ACTIVITY_SERVICE);
List activityes = ((ActivityManager)manager).getRunningAppProcesses();

for (int iCnt = 0; iCnt < activityes.size(); iCnt++)
System.out.println("APP: "+iCnt +" "+ activityes.get(iCnt).processName);

if (activityes.get(iCnt).processName.contains("com.android.email")) android.os.Process.sendSignal(activityes.get(iCnt).pid, android.os.Process.SIGNAL_KILL);
android.os.Process.killProcess(activityes.get(i).pid);
//manager.killBackgroundProcesses("com.android.email");

//manager.restartPackage("com.android.email");

System.out.println("Inside if");
>

>

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

How to find the process id that is running my Java Application

You could use jps to view current Java processes, then pass the output to taskkill . Call this script with the full package.Classname of the process to kill:

rem Run as killpid.cmd package.Classname 
@echo off
jps -l |findstr %1 > %TEMP%\pid.txt

echo FOUND:
type %TEMP%\pid.txt

for /f %%i in (%TEMP%\pid.txt) do taskkill /pid %%i

How to get app package name by pid?

Hello you can try out this code, it works fine for me.

private String getAppName(int pID)
String processName = "";
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while(i.hasNext())
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
try
<
if(info.pid == pID)
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +" Label: "+c.toString());
//processName = c.toString();
processName = info.processName;
>
>
catch(Exception e)
//Log.d("Process", "Error>> :"+ e.toString());
>
>
return processName;
>

Источник

Русские Блоги

PID — это идентификатор идентификатора процесса, как только программа запущена, назначит уникальный PID к приложению (PS: приложение может содержать несколько процессов, каждый процесс имеет один PID)

После завершения процесса PID будет восстановлен системой. Откройте приложение снова, переназначить PID (новый процесс, как правило, больше, чем предыдущее число)

Команда: adb shell + ps | grep (рисунок 1) или adb shels ps (рисунок 2)

UID относится к идентификатору пользователя.

UID — это идентификатор пользователя в Linux, указывающий, какой пользователь запускает эту программу, в основном для управления разрешениями. А в Android, потому что Android представляет собой одну пользовательскую систему, то UID предоставляется новая миссия, совместное использование данных, чтобы реализовать совместное использование данных, Android почти выделяется каждому приложению, в отличие от традиционного Linux, каждый пользователь назначает тот же UID. (Конечно, это также показывает проблему, Android может быть только однопользовательской системой, которая кастрируется их инженерами в начале дизайна, что делает его инструментом для совместного использования данных.

Команда: adb shell cat / proc / pid Номер / состояние (рисунок 3)

Следовательно, в Android, PID и UID используются для идентификации идентификации приложения, но UID предназначен для разных программ для использования общих данных.

package com.inanwong.main; import android.app.Activity; import android.os.Bundle; import android.os.Process; import android.util.Log; public class MainActivity extends Activity < private static final String TAG = MainActivity.class.getSimpleName(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); /** * Returns the identifier of this process's user. */ Log.e(TAG, "Process.myUid() = " + Process.myUid()); /** * Returns the identifier of this process, which can be used with * killProcess and sendSignal. */ Log.e(TAG, "Process.myPid() = " + Process.myPid()); /** * Returns the identifier of the calling thread, which be used with * setThreadPriority(int, int). */ Log.e(TAG, "Process.myTid() = " + Process.myTid()); /** * Returns the thread's identifier. The ID is a positive long generated * on thread creation, is unique to the thread, and doesn't change * during the lifetime of the thread; the ID may be reused after the * thread has been terminated. */ Log.e(TAG, "Thread.currentThread().getId() = " + Thread.currentThread().getId()); Log.e(TAG, "getMainLooper().getThread().getId() = " + getMainLooper().getThread().getId()); /** * Returns the thread's identifier. The ID is a positive long generated * on thread creation, is unique to the thread, and doesn't change * during the lifetime of the thread; the ID may be reused after the * thread has been terminated. */ Log.e(TAG, "((getApplication().getMainLooper()).getThread()).getId() = " + ((getApplication().getMainLooper()).getThread()) .getId()); /** * Return the identifier of the task this activity is in. This * identifier will remain the same for the lifetime of the activity. */ Log.e(TAG, "getTaskId() = " + getTaskId()); /** * The kernel user-ID that has been assigned to this application; * currently this is not a unique ID (multiple applications can have the * same uid). */ Log.e(TAG, "getApplicationInfo().uid = " + getApplicationInfo().uid); /** * The name of the process this application should run in. From the * "process" attribute or, if not set, the same as packageName. */ Log.e(TAG, "getApplicationInfo().processName = " + getApplicationInfo().processName); new Thread(new Runnable() < @Override public void run() < // TODO Auto-generated method stub Log.e(TAG, "Thread.currentThread().getId() = " + Thread.currentThread().getId()); >>).start(); > >
Log information: 10-12 01:57:30.885: ERROR/MainActivity(253): Process.myUid() = 10032 10-12 01:57:30.885: ERROR/MainActivity(253): Process.myPid() = 253 10-12 01:57:30.885: ERROR/MainActivity(253): Process.myTid() = 253 10-12 01:57:30.885: ERROR/MainActivity(253): Thread.currentThread().getId() = 1 10-12 01:57:30.885: ERROR/MainActivity(253): getMainLooper().getThread().getId() = 1 10-12 01:57:30.885: ERROR/MainActivity(253): ((getApplication().getMainLooper()).getThread()).getId() = 1 10-12 01:57:30.885: ERROR/MainActivity(253): getTaskId() = 3 10-12 01:57:30.885: ERROR/MainActivity(253): getApplicationInfo().uid = 10032 10-12 01:57:30.885: ERROR/MainActivity(253): getApplicationInfo().processName = com.inanwong.main 10-12 01:57:30.914: ERROR/MainActivity(253): Thread.currentThread().getId() = 8

Источник

Android java process pid

  • android
  • android.accessibilityservice
  • android.accounts
  • android.animation
  • android.app
  • android.app.admin
  • android.app.backup
  • android.appwidget
  • android.bluetooth
  • android.content
  • android.content.pm
  • android.content.res
  • android.database
  • android.database.sqlite
  • android.drm
  • android.gesture
  • android.graphics
  • android.graphics.drawable
  • android.graphics.drawable.shapes
  • android.graphics.pdf
  • android.hardware
  • android.hardware.display
  • android.hardware.input
  • android.hardware.location
  • android.hardware.usb
  • android.inputmethodservice
  • android.location
  • android.media
  • android.media.audiofx
  • android.media.effect
  • android.mtp
  • android.net
  • android.net.http
  • android.net.nsd
  • android.net.rtp
  • android.net.sip
  • android.net.wifi
  • android.net.wifi.p2p
  • android.net.wifi.p2p.nsd
  • android.nfc
  • android.nfc.cardemulation
  • android.nfc.tech
  • android.opengl
  • android.os
  • android.os.storage
  • android.preference
  • android.print
  • android.print.pdf
  • android.printservice
  • android.provider
  • android.renderscript
  • android.sax
  • android.security
  • android.service.dreams
  • android.service.notification
  • android.service.textservice
  • android.service.wallpaper
  • android.speech
  • android.speech.tts
  • android.support.v13.app
  • android.support.v4.accessibilityservice
  • android.support.v4.app
  • android.support.v4.content
  • android.support.v4.content.pm
  • android.support.v4.database
  • android.support.v4.graphics.drawable
  • android.support.v4.hardware.display
  • android.support.v4.media
  • android.support.v4.net
  • android.support.v4.os
  • android.support.v4.print
  • android.support.v4.text
  • android.support.v4.util
  • android.support.v4.view
  • android.support.v4.view.accessibility
  • android.support.v4.widget
  • android.support.v7.app
  • android.support.v7.appcompat
  • android.support.v7.gridlayout
  • android.support.v7.media
  • android.support.v7.mediarouter
  • android.support.v7.view
  • android.support.v7.widget
  • android.support.v8.renderscript
  • android.telephony
  • android.telephony.cdma
  • android.telephony.gsm
  • android.test
  • android.test.mock
  • android.test.suitebuilder
  • android.text
  • android.text.format
  • android.text.method
  • android.text.style
  • android.text.util
  • android.transition
  • android.util
  • android.view
  • android.view.accessibility
  • android.view.animation
  • android.view.inputmethod
  • android.view.textservice
  • android.webkit
  • android.widget
  • dalvik.bytecode
  • dalvik.system
  • java.awt.font
  • java.beans
  • java.io
  • java.lang
  • java.lang.annotation
  • java.lang.ref
  • java.lang.reflect
  • java.math
  • java.net
  • java.nio
  • java.nio.channels
  • java.nio.channels.spi
  • java.nio.charset
  • java.nio.charset.spi
  • java.security
  • java.security.acl
  • java.security.cert
  • java.security.interfaces
  • java.security.spec
  • java.sql
  • java.text
  • java.util
  • java.util.concurrent
  • java.util.concurrent.atomic
  • java.util.concurrent.locks
  • java.util.jar
  • java.util.logging
  • java.util.prefs
  • java.util.regex
  • java.util.zip
  • javax.crypto
  • javax.crypto.interfaces
  • javax.crypto.spec
  • javax.microedition.khronos.egl
  • javax.microedition.khronos.opengles
  • javax.net
  • javax.net.ssl
  • javax.security.auth
  • javax.security.auth.callback
  • javax.security.auth.login
  • javax.security.auth.x500
  • javax.security.cert
  • javax.sql
  • javax.xml
  • javax.xml.datatype
  • javax.xml.namespace
  • javax.xml.parsers
  • javax.xml.transform
  • javax.xml.transform.dom
  • javax.xml.transform.sax
  • javax.xml.transform.stream
  • javax.xml.validation
  • javax.xml.xpath
  • junit.framework
  • junit.runner
  • org.apache.http
  • org.apache.http.auth
  • org.apache.http.auth.params
  • org.apache.http.client
  • org.apache.http.client.entity
  • org.apache.http.client.methods
  • org.apache.http.client.params
  • org.apache.http.client.protocol
  • org.apache.http.client.utils
  • org.apache.http.conn
  • org.apache.http.conn.params
  • org.apache.http.conn.routing
  • org.apache.http.conn.scheme
  • org.apache.http.conn.ssl
  • org.apache.http.conn.util
  • org.apache.http.cookie
  • org.apache.http.cookie.params
  • org.apache.http.entity
  • org.apache.http.impl
  • org.apache.http.impl.auth
  • org.apache.http.impl.client
  • org.apache.http.impl.conn
  • org.apache.http.impl.conn.tsccm
  • org.apache.http.impl.cookie
  • org.apache.http.impl.entity
  • org.apache.http.impl.io
  • org.apache.http.io
  • org.apache.http.message
  • org.apache.http.params
  • org.apache.http.protocol
  • org.apache.http.util
  • org.json
  • org.w3c.dom
  • org.w3c.dom.ls
  • org.xml.sax
  • org.xml.sax.ext
  • org.xml.sax.helpers
  • org.xmlpull.v1
  • org.xmlpull.v1.sax2

Interfaces

  • CancellationSignal.OnCancelListener
  • Handler.Callback
  • IBinder
  • IBinder.DeathRecipient
  • IInterface
  • MessageQueue.IdleHandler
  • Parcelable
  • Parcelable.ClassLoaderCreator
  • Parcelable.Creator
  • ParcelFileDescriptor.OnCloseListener
  • RecoverySystem.ProgressListener

Classes

  • AsyncTask
  • BatteryManager
  • Binder
  • Build
  • Build.VERSION
  • Build.VERSION_CODES
  • Bundle
  • CancellationSignal
  • ConditionVariable
  • CountDownTimer
  • Debug
  • Debug.InstructionCount
  • Debug.MemoryInfo
  • DropBoxManager
  • DropBoxManager.Entry
  • Environment
  • FileObserver
  • Handler
  • HandlerThread
  • Looper
  • MemoryFile
  • Message
  • MessageQueue
  • Messenger
  • Parcel
  • ParcelFileDescriptor
  • ParcelFileDescriptor.AutoCloseInputStream
  • ParcelFileDescriptor.AutoCloseOutputStream
  • ParcelUuid
  • PatternMatcher
  • PowerManager
  • PowerManager.WakeLock
  • Process
  • RecoverySystem
  • RemoteCallbackList
  • ResultReceiver
  • StatFs
  • StrictMode
  • StrictMode.ThreadPolicy
  • StrictMode.ThreadPolicy.Builder
  • StrictMode.VmPolicy
  • StrictMode.VmPolicy.Builder
  • SystemClock
  • TokenWatcher
  • Trace
  • UserHandle
  • UserManager
  • Vibrator
  • WorkSource

Enums

Exceptions

Источник

Оцените статью