Java lang process android

Руководство по java.lang.API процесса

Краткое и практическое руководство по API процессов Java.

Автор: baeldung
Дата записи

1. введение

В этом уроке мы подробно рассмотрим Процесс API .

Для более поверхностного изучения того, как использовать Process для выполнения команды оболочки, мы можем обратиться к нашему предыдущему учебнику здесь .

Процесс, на который он ссылается, является выполняемым приложением. Класс Process предоставляет методы для взаимодействия с этими процессами, включая извлечение выходных данных, выполнение ввода, мониторинг жизненного цикла, проверку состояния выхода и его уничтожение (уничтожение).

2. Использование класса Process для компиляции и запуска Java-программы

Давайте рассмотрим пример компиляции и запуска другой программы Java с помощью Process API:

Таким образом, возможности выполнения Java-кода в рамках существующего Java-кода практически безграничны.

3. Процесс Создания

Наше Java – приложение может вызывать любое приложение, работающее в нашей компьютерной системе, в соответствии с ограничениями операционной системы.

Поэтому мы можем выполнять заявки. Давайте посмотрим, каковы различные варианты использования, которые мы можем запустить, используя API процесса.

Класс ProcessBuilder позволяет нам создавать подпроцессы в нашем приложении.

Давайте посмотрим демонстрацию открытия приложения Блокнота на базе Windows:

4. Процесс Разрушения

Процесс также предоставляет нам методы для уничтожения подпроцессов или процессов. Хотя способ уничтожения приложения зависит от платформы .

Давайте рассмотрим различные варианты использования, которые возможны.

4.1. Уничтожение процесса по ссылке

Допустим, мы используем ОС Windows и хотим создать приложение Блокнота и уничтожить его.

Как и прежде, мы можем создать экземпляр приложения Notepad с помощью класса ProcessBuilder и метода start () .

Затем мы можем вызвать метод destroy() для нашего объекта Process .

4.2. Уничтожение процесса по идентификатору

Мы также можем убивать процессы, запущенные в нашей операционной системе, которые не могут быть созданы нашим приложением.

При этом следует соблюдать осторожность, так как мы можем неосознанно уничтожить критический процесс, который может сделать операционную систему нестабильной .

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

Давайте рассмотрим пример:

4.3. Разрушение процесса силой

При выполнении метода destroy() подпроцесс будет уничтожен, как мы видели ранее в этой статье.

В случае, когда уничтожать() не работает, у нас есть возможность Разрушительно() .

Мы всегда должны начинать с метода destroy () . После этого мы можем выполнить быструю проверку подпроцесса, выполнив IsAlive() .

Если он возвращает true, то выполните destroyForcibly() :

5. Ожидание завершения процесса

У нас также есть два перегруженных метода, с помощью которых мы можем гарантировать, что сможем дождаться завершения процесса.

5.1. подождите()

Когда этот метод выполняется, он помещает текущий поток процесса выполнения в состояние ожидания блокировки, если подпроцесс не будет завершен .

Давайте рассмотрим пример:

Из приведенного выше примера видно, что для продолжения выполнения текущего потока он будет продолжать ждать завершения потока подпроцесса. Как только подпроцесс завершится, текущий поток продолжит свое выполнение.

Читайте также:  Перепрошивка головного устройства андроид

5.2. waitfor(длительный тайм-аут, время ожидания)

Когда этот метод выполняется, он помещает текущий поток процесса выполнения в состояние ожидания блокировки, если только подпроцесс не будет завершен или не закончится время .

Давайте рассмотрим пример:

Из приведенного выше примера видно, что для продолжения выполнения текущего потока он будет продолжать ждать завершения потока подпроцесса или истечения указанного интервала времени.

Когда этот метод выполняется, он возвращает логическое значение true, если подпроцесс вышел, или логическое значение false, если время ожидания истекло до выхода подпроцесса.

6. Значение выхода()

При запуске этого метода текущий поток не будет ждать завершения или уничтожения подпроцесса, однако он вызовет исключение IllegalThreadStateException , если подпроцесс не будет завершен.

По – другому, если подпроцесс был успешно завершен, это приведет к значению выхода процесса .

Это может быть любое возможное положительное целое число.

Давайте рассмотрим пример, когда метод exitValue() возвращает положительное целое число, когда подпроцесс был успешно завершен:

7. IsAlive()

Когда мы хотим выполнить бизнес-обработку, которая является субъективной, независимо от того, является ли процесс живым или нет.

Мы можем выполнить быструю проверку, чтобы определить, является ли процесс живым или нет, который возвращает логическое значение.

Давайте рассмотрим краткий пример этого:

8. Обработка потоков процессов

По умолчанию созданный подпроцесс не имеет своего терминала или консоли. Все его стандартные операции ввода-вывода (например, stdin, stdout, stderr) будут отправлены родительскому процессу. Таким образом, родительский процесс может использовать эти потоки для подачи входных данных в подпроцесс и получения выходных данных из него.

Следовательно, это дает нам огромную гибкость, поскольку дает нам контроль над вводом/выводом нашего подпроцесса.

8.1. getErrorStream()

Интересно, что мы можем извлечь ошибки, сгенерированные из подпроцесса, и затем выполнить бизнес-обработку.

После этого мы можем выполнить конкретные проверки бизнес-обработки в соответствии с нашими требованиями.

Давайте рассмотрим пример:

8.2. getInputStream()

Мы также можем извлекать выходные данные, генерируемые подпроцессом, и потреблять их в родительском процессе, что позволяет обмениваться информацией между процессами:

8.3. getOutputStream()

Мы можем отправлять входные данные в подпроцесс из родительского процесса:

8.4. Фильтрация технологических потоков

Это вполне допустимый вариант использования для взаимодействия с выборочными запущенными процессами.

Process предоставляет нам возможность выборочно фильтровать запущенные процессы на основе определенного предиката.

После этого мы можем выполнять бизнес-операции с этим набором выборочных процессов:

9. Заключение

Process – это мощный класс для взаимодействия на уровне операционной системы. Запуск команд терминала, а также запуск, мониторинг и уничтожение приложений.

Для получения дополнительной информации об API процессов Java 9 ознакомьтесь с нашей статьей здесь .

Как всегда, вы найдете источники на Github .

Источник

Java lang process android

The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts.

By default, the created process does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream() , getInputStream() , and getErrorStream() . The parent process uses these streams to feed input to and get output from the process. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the process may cause the process to block, or even deadlock.

Читайте также:  Android тас что это

The process is not killed when there are no more references to the Process object, but rather the process continues executing asynchronously.

There is no requirement that the process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object.

As of 1.5, ProcessBuilder.start() is the preferred way to create a Process .

Subclasses of Process should override the onExit() and toHandle() methods to provide a fully functional Process including the process id, information about the process, direct children, and direct children plus descendants of those children of the process. Delegating to the underlying Process or ProcessHandle is typically easiest and most efficient.

Источник

Process Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

The ProcessBuilder#start() and Runtime#exec(String[],String[],File) Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

A constructor used when creating managed representations of JNI objects; called by the runtime.

Properties

Returns the runtime class of this Object .

(Inherited from Object) ErrorStream

Returns an input stream that is connected to the error stream (stderr) of the native process represented by this object.

The handle to the underlying Android instance.

(Inherited from Object) InputStream

Returns an input stream that is connected to the standard output stream (stdout) of the native process represented by this object.

Tests whether the subprocess represented by this Process is alive.

Returns an output stream that is connected to the standard input stream (stdin) of the native process represented by this object.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Creates and returns a copy of this object.

(Inherited from Object) Destroy()

Kills the subprocess.

Kills the subprocess.

Dispose() (Inherited from Object) Dispose(Boolean) (Inherited from Object) Equals(Object)

Indicates whether some other object is «equal to» this one.

(Inherited from Object) ExitValue()

Returns the exit value for the subprocess.

Returns a hash code value for the object.

(Inherited from Object) JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Читайте также:  Тема хищник для андроид

(Inherited from Object) Notify()

Wakes up a single thread that is waiting on this object’s monitor.

(Inherited from Object) NotifyAll()

Wakes up all threads that are waiting on this object’s monitor.

(Inherited from Object) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object) ToArray () (Inherited from Object) ToString()

Returns a string representation of the object.

(Inherited from Object) UnregisterFromRuntime() (Inherited from Object) Wait()

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64, Int32)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) WaitFor()

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Package java.lang

    Interface Summary
    Interface Description
    Appendable
    Class Summary
    Class Description
    Boolean
    Exception Summary
    Exception Description
    ArithmeticException
    Error Summary
    Error Description
    AbstractMethodError
    Annotation Types Summary
    Annotation Type Description
    Deprecated

    Package java.lang Description

    Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean , Character , Integer , Long , Float , and Double serve this purpose. An object of type Double , for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode. The Void class is a non-instantiable class that holds a reference to a Class object representing the type void.

    The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String , StringBuffer , and StringBuilder similarly provide commonly used operations on character strings.

    Classes ClassLoader , Process , ProcessBuilder , Runtime , SecurityManager , and System provide «system operations» that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies.

    Class Throwable encompasses objects that may be thrown by the throw statement. Subclasses of Throwable represent errors and exceptions.

    Character Encodings

    Submit a bug or feature
    For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
    Copyright © 1993, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

    Источник

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