Documentation ¶
Overview ¶
package adb is a Go interface to the Android Debug Bridge (adb).
See cmd/demo/demo.go for an example of how to use this library.
The client/server spec is defined at https://android.googlesource.com/platform/system/core/+/master/adb/OVERVIEW.TXT.
WARNING This library is under heavy development, and its API is likely to change without notice.
Index ¶
- Constants
- Variables
- func ErrorWithCauseChain(err error) string
- func HasErrCode(err error, code ErrCode) bool
- type Adb
- func (c *Adb) Device(descriptor DeviceDescriptor) *Device
- func (c *Adb) Dial() (*wire.Conn, error)
- func (c *Adb) KillServer() error
- func (c *Adb) ListDeviceSerials() ([]string, error)
- func (c *Adb) ListDevices() ([]*DeviceInfo, error)
- func (c *Adb) ListDevicesInfo() ([]string, []string, error)
- func (c *Adb) NewDeviceWatcher() *DeviceWatcher
- func (c *Adb) ServerVersion() (int, error)
- func (c *Adb) StartServer() error
- type AsyncWriter
- type Device
- func (c *Device) DeviceInfo() (*DeviceInfo, error)
- func (c *Device) DevicePath() (string, error)
- func (c *Device) DoSyncFile(path string, rd io.ReadCloser, size int64, perms os.FileMode) (aw *AsyncWriter, err error)
- func (c *Device) DoSyncHTTPFile(dst string, srcUrl string, perms os.FileMode) (aw *AsyncWriter, err error)
- func (c *Device) DoSyncLocalFile(dst string, src string, perms os.FileMode) (aw *AsyncWriter, err error)
- func (c *Device) Forward(local, remote ForwardSpec) error
- func (c *Device) ForwardList() (fs []ForwardPair, err error)
- func (c *Device) ForwardRemove(local ForwardSpec) error
- func (c *Device) ForwardRemoveAll() error
- func (c *Device) ForwardToFreePort(remote ForwardSpec) (port int, err error)
- func (c *Device) KillProcessByName(name string, sig syscall.Signal) error
- func (c *Device) ListDirEntries(path string) (*DirEntries, error)
- func (c *Device) ListProcesses() (ps []Process, err error)
- func (c *Device) OpenCmdInContext(conn *wire.Conn, cmd string, args ...string) (*wire.Conn, error)
- func (c *Device) OpenCommand(cmd string, args ...string) (conn *wire.Conn, err error)
- func (c *Device) OpenRead(path string) (io.ReadCloser, error)
- func (c *Device) OpenWrite(path string, perms os.FileMode, mtime time.Time) (io.WriteCloser, error)
- func (c *Device) Properties() (props map[string]string, err error)
- func (c *Device) Pull(remotePath, localPath string) (int64, error)
- func (c *Device) Push(localPath, remotePath string) int64
- func (c *Device) Remount() (string, error)
- func (c *Device) RunCommand(cmd string, args ...string) (string, error)
- func (c *Device) RunCommandInContext(conn *wire.Conn, cmd string, args ...string) (*wire.Conn, string, error)
- func (c *Device) RunCommandWithExitCode(cmd string, args ...string) (string, int, error)
- func (c *Device) Serial() (string, error)
- func (c *Device) Stat(path string) (*DirEntry, error)
- func (c *Device) StatPackage(packageName string) (pi PackageInfo, err error)
- func (c *Device) State() (DeviceState, error)
- func (c *Device) String() string
- func (c *Device) WriteHttpToFile(path string, urlStr string, perms os.FileMode) (written int64, err error)
- func (c *Device) WriteToFile(path string, rd io.Reader, perms os.FileMode) (written int64, err error)
- type DeviceDescriptor
- type DeviceInfo
- type DeviceState
- type DeviceStateChangedEvent
- type DeviceWatcher
- type Dialer
- type DirEntries
- type DirEntry
- type ErrCode
- type ForwardPair
- type ForwardSpec
- type PackageInfo
- type Process
- type ServerConfig
- type ShellExitError
Examples ¶
Constants ¶
const ( // host:transport-any and host:<request> DeviceAny deviceDescriptorType = iota // host:transport:<serial> and host-serial:<serial>:<request> DeviceSerial // host:transport-usb and host-usb:<request> DeviceUsb // host:transport-local and host-local:<request> DeviceLocal )
const ( AssertionError = ErrCode(errors.AssertionError) ParseError = ErrCode(errors.ParseError) // The server was not available on the requested port. ServerNotAvailable = ErrCode(errors.ServerNotAvailable) // General network error communicating with the server. NetworkError = ErrCode(errors.NetworkError) // The connection to the server was reset in the middle of an operation. Server probably died. ConnectionResetError = ErrCode(errors.ConnectionResetError) // The server returned an error message, but we couldn't parse it. AdbError = ErrCode(errors.AdbError) // The server returned a "device not found" error. DeviceNotFound = ErrCode(errors.DeviceNotFound) // Tried to perform an operation on a path that doesn't exist on the device. FileNoExistError = ErrCode(errors.FileNoExistError) )
const ( AdbExecutableName = "adb" // Default port the adb server listens on. AdbPort = 5037 )
Variables ¶
var ( FProtocolTcp = "tcp" FProtocolAbstract = "localabstract" FProtocolReserved = "localreserved" FProtocolFilesystem = "localfilesystem" )
var ErrPackageNotExist = sysErrors.New("package not exist")
var MtimeOfClose = time.Time{}
MtimeOfClose should be passed to OpenWrite to set the file modification time to the time the Close method is called.
Functions ¶
func ErrorWithCauseChain ¶
ErrorWithCauseChain formats err and all its causes if it's an *errors.Err, else returns err.Error().
func HasErrCode ¶
HasErrCode returns true if err is an *errors.Err and err.Code == code.
Types ¶
type Adb ¶
type Adb struct {
// contains filtered or unexported fields
}
Adb communicates with host services on the adb server.
Eg.
client := adb.New() client.ListDevices()
See list of services at https://android.googlesource.com/platform/system/core/+/master/adb/SERVICES.TXT.
TODO(z): Finish implementing host services.
func NewWithConfig ¶
func NewWithConfig(config ServerConfig) (*Adb, error)
func (*Adb) Device ¶
func (c *Adb) Device(descriptor DeviceDescriptor) *Device
func (*Adb) KillServer ¶
KillServer tells the server to quit immediately.
Corresponds to the command:
adb kill-server
func (*Adb) ListDeviceSerials ¶
ListDeviceSerials returns the serial numbers of all attached devices.
Corresponds to the command:
adb devices
func (*Adb) ListDevices ¶
func (c *Adb) ListDevices() ([]*DeviceInfo, error)
ListDevices returns the list of connected devices.
Corresponds to the command:
adb devices -l
func (*Adb) NewDeviceWatcher ¶
func (c *Adb) NewDeviceWatcher() *DeviceWatcher
func (*Adb) ServerVersion ¶
ServerVersion asks the ADB server for its internal version number.
func (*Adb) StartServer ¶
Starts the adb server if it’s not running.
type AsyncWriter ¶
type AsyncWriter struct { Done chan bool DoneCopy chan bool // for debug C chan bool TotalSize int64 // contains filtered or unexported fields }
func (*AsyncWriter) BytesCompleted ¶
func (a *AsyncWriter) BytesCompleted() int64
BytesCompleted returns the total number of bytes which have been copied to the destination
func (*AsyncWriter) Cancel ¶
func (a *AsyncWriter) Cancel() error
func (*AsyncWriter) Progress ¶
func (a *AsyncWriter) Progress() float64
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device communicates with a specific Android device. To get an instance, call Device() on an Adb.
func (*Device) DeviceInfo ¶
func (c *Device) DeviceInfo() (*DeviceInfo, error)
func (*Device) DevicePath ¶
func (*Device) DoSyncFile ¶
func (c *Device) DoSyncFile(path string, rd io.ReadCloser, size int64, perms os.FileMode) (aw *AsyncWriter, err error)
DoWriteFile return an object, use this object can Cancel write and get Process
func (*Device) DoSyncHTTPFile ¶
func (*Device) DoSyncLocalFile ¶
func (c *Device) DoSyncLocalFile(dst string, src string, perms os.FileMode) (aw *AsyncWriter, err error)
Example ¶
package main import ( "log" adb "github.com/thinkhy/go-adb" ) func main() { adbc, _ := adb.New() dev := adbc.Device(adb.AnyUsbDevice()) sync, err := dev.DoSyncLocalFile("/data/local/tmp/tmp.txt", "local.txt", 0644) if err != nil { log.Fatal(err) } Loop: for { select { case <-sync.C: log.Printf("transfered %v / %v bytes (%.2f%%)", sync.BytesCompleted(), sync.TotalSize, 100*sync.Progress()) case <-sync.DoneCopy: log.Printf("finish io copy") case <-sync.Done: log.Printf("finish system copy, this is final") break Loop } } log.Printf("copy error: %s", sync.Err()) }
Output:
func (*Device) Forward ¶
func (c *Device) Forward(local, remote ForwardSpec) error
Forward remote connection to local
func (*Device) ForwardList ¶
func (c *Device) ForwardList() (fs []ForwardPair, err error)
ForwardList returns list with struct ForwardPair If no device serial specified all devices's forward list will returned
func (*Device) ForwardRemove ¶
func (c *Device) ForwardRemove(local ForwardSpec) error
ForwardRemove specified forward
func (*Device) ForwardRemoveAll ¶
ForwardRemoveAll cancel all exists forwards
func (*Device) ForwardToFreePort ¶
func (c *Device) ForwardToFreePort(remote ForwardSpec) (port int, err error)
ForwardToFreePort return random generated port If forward already exists, just return current forworded port
func (*Device) KillProcessByName ¶
KillProcessByName return if killed success
func (*Device) ListDirEntries ¶
func (c *Device) ListDirEntries(path string) (*DirEntries, error)
func (*Device) ListProcesses ¶
ListProcesses return list of Process
func (*Device) OpenCmdInContext ¶
func (*Device) OpenCommand ¶
func (*Device) OpenWrite ¶
OpenWrite opens the file at path on the device, creating it with the permissions specified by perms if necessary, and returns a writer that writes to the file. The files modification time will be set to mtime when the WriterCloser is closed. The zero value is TimeOfClose, which will use the time the Close method is called as the modification time.
func (*Device) Properties ¶
Properties extract info from $ adb shell getprop
func (*Device) Remount ¶
Remount, from the official adb command’s docs:
Ask adbd to remount the device's filesystem in read-write mode, instead of read-only. This is usually necessary before performing an "adb sync" or "adb push" request. This request may not succeed on certain builds which do not allow that.
Source: https://android.googlesource.com/platform/system/core/+/master/adb/SERVICES.TXT
func (*Device) RunCommand ¶
RunCommand runs the specified commands on a shell on the device.
From the Android docs:
Run 'command arg1 arg2 ...' in a shell on the device, and return its output and error streams. Note that arguments must be separated by spaces. If an argument contains a space, it must be quoted with double-quotes. Arguments cannot contain double quotes or things will go very wrong. Note that this is the non-interactive version of "adb shell"
Source: https://android.googlesource.com/platform/system/core/+/master/adb/SERVICES.TXT
This method quotes the arguments for you, and will return an error if any of them contain double quotes.
Because the adb shell converts all "\n" into "\r\n", so here we convert it back (maybe not good for binary output)
func (*Device) RunCommandInContext ¶
func (*Device) RunCommandWithExitCode ¶
RunCommandWithExitCode use a little tricky to get exit code
The tricky is append "; echo :$?" to the command, and parse out the exit code from output
func (*Device) StatPackage ¶
func (c *Device) StatPackage(packageName string) (pi PackageInfo, err error)
StatPackage returns PackageInfo If package not found, err will be ErrPackageNotExist
func (*Device) State ¶
func (c *Device) State() (DeviceState, error)
type DeviceDescriptor ¶
type DeviceDescriptor struct {
// contains filtered or unexported fields
}
func AnyDevice ¶
func AnyDevice() DeviceDescriptor
func AnyLocalDevice ¶
func AnyLocalDevice() DeviceDescriptor
func AnyUsbDevice ¶
func AnyUsbDevice() DeviceDescriptor
func DeviceWithSerial ¶
func DeviceWithSerial(serial string) DeviceDescriptor
func (DeviceDescriptor) String ¶
func (d DeviceDescriptor) String() string
type DeviceInfo ¶
type DeviceInfo struct { // Always set. Serial string Status string // Product, device, and model are not set in the short form. Product string Model string DeviceInfo string // Only set for devices connected via USB. Usb string }
func (*DeviceInfo) IsUsb ¶
func (d *DeviceInfo) IsUsb() bool
IsUsb returns true if the device is connected via USB.
type DeviceState ¶
type DeviceState int8
DeviceState represents one of the 3 possible states adb will report devices. A device can be communicated with when it's in StateOnline. A USB device will make the following state transitions:
Plugged in: StateDisconnected->StateOffline->StateOnline Unplugged: StateOnline->StateDisconnected
const ( StateInvalid DeviceState = iota StateDisconnected StateOffline StateConnecting StateOnline )
func (DeviceState) String ¶
func (i DeviceState) String() string
type DeviceStateChangedEvent ¶
type DeviceStateChangedEvent struct { Serial string OldState DeviceState NewState DeviceState }
DeviceStateChangedEvent represents a device state transition. Contains the device’s old and new states, but also provides methods to query the type of state transition.
func (DeviceStateChangedEvent) CameOnline ¶
func (s DeviceStateChangedEvent) CameOnline() bool
CameOnline returns true if this event represents a device coming online.
func (DeviceStateChangedEvent) WentOffline ¶
func (s DeviceStateChangedEvent) WentOffline() bool
WentOffline returns true if this event represents a device going offline.
type DeviceWatcher ¶
type DeviceWatcher struct {
// contains filtered or unexported fields
}
DeviceWatcher publishes device status change events. If the server dies while listening for events, it restarts the server.
func (*DeviceWatcher) C ¶
func (w *DeviceWatcher) C() <-chan DeviceStateChangedEvent
C returns a channel than can be received on to get events. If an unrecoverable error occurs, or Shutdown is called, the channel will be closed.
func (*DeviceWatcher) Err ¶
func (w *DeviceWatcher) Err() error
Err returns the error that caused the channel returned by C to be closed, if C is closed. If C is not closed, its return value is undefined.
func (*DeviceWatcher) Shutdown ¶
func (w *DeviceWatcher) Shutdown()
Shutdown stops the watcher from listening for events and closes the channel returned from C.
type DirEntries ¶
type DirEntries struct {
// contains filtered or unexported fields
}
DirEntries iterates over directory entries.
func (*DirEntries) Close ¶
func (entries *DirEntries) Close() error
Close closes the connection to the adb. Next() will call Close() before returning false.
func (*DirEntries) Entry ¶
func (entries *DirEntries) Entry() *DirEntry
func (*DirEntries) Err ¶
func (entries *DirEntries) Err() error
func (*DirEntries) Next ¶
func (entries *DirEntries) Next() bool
func (*DirEntries) ReadAll ¶
func (entries *DirEntries) ReadAll() (result []*DirEntry, err error)
ReadAllDirEntries reads all the remaining directory entries into a slice, closes self, and returns any error. If err is non-nil, result will contain any entries read until the error occurred.
type ForwardPair ¶
type ForwardPair struct { Serial string Local ForwardSpec Remote ForwardSpec }
type ForwardSpec ¶
func (ForwardSpec) Port ¶
func (f ForwardSpec) Port() (int, error)
func (ForwardSpec) String ¶
func (f ForwardSpec) String() string
type PackageInfo ¶
type ServerConfig ¶
type ServerConfig struct { // Path to the adb executable. If empty, the PATH environment variable will be searched. PathToAdb string // Host and port the adb server is listening on. // If not specified, will use the default port on localhost. Host string Port int // Dialer used to connect to the adb server. Dialer // contains filtered or unexported fields }
type ShellExitError ¶
func (ShellExitError) Error ¶
func (s ShellExitError) Error() string
Source Files ¶
- adb.go
- asyncwriter.go
- device.go
- device_descriptor.go
- device_extra.go
- device_info.go
- device_state.go
- device_watcher.go
- devicedescriptortype_string.go
- devicestate_string.go
- dialer.go
- dir_entries.go
- doc.go
- error.go
- executable.go
- executable_unix.go
- server.go
- sync_client.go
- sync_file_reader.go
- sync_file_writer.go
- util.go
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
demo
An app demonstrating most of the library's features.
|
An app demonstrating most of the library's features. |
raw-adb
A simple tool for sending raw messages to an adb server.
|
A simple tool for sending raw messages to an adb server. |
internal
|
|
Package wire implements the low-level part of the client/server wire protocol.
|
Package wire implements the low-level part of the client/server wire protocol. |