Files
Android-pyApi/android_pyapi/__init__.py
T
shuiyu1123 39b1da37c9 feat: 全面完善API — 补全核心类方法、存根转真实实现、Exception体系扩展
核心类方法补全:
- Activity: +20方法 (requestWindowFeature, setTitle/getTitle, onKeyDown/onKeyUp, enterPictureInPictureMode, getReferrer, isTaskRoot, navigateUpTo等)
- Fragment: +15方法 (getChildFragmentManager, getParentFragment, requireContext/requireActivity, setMenuVisibility等)
- Intent: +20方法 (getParcelableExtra, setComponent/getComponent, getDataString, getScheme, putExtras等)
- View: +20方法 (setLabelFor, setRotationX/Y, setForeground, setBackgroundTintList等)
- KeyEvent: +7方法 (getCharacters, isSystem, isPrintingKey, isModifierKey, startTracking等)
- Paint: +12方法 (setStrokeCap/Join, getTextBounds, setBlendMode, setLetterSpacing等)
- Notification.Builder: +10方法 (setProgress, setShowWhen, setOnlyAlertOnce, setSound等)

存根转真实实现:
- TrafficStats: 读取 /proc/net/dev 返回真实网络流量
- RecyclerView.Adapter: 观察者模式触发通知
- BaseAdapter: 观察者模式触发通知
- ExifInterface: 使用PIL实现图片翻转/旋转
- Process: 使用os.kill实现进程信号
- FileUtils: 真实文件I/O
- SharedPreferences: 监听器模式
- TelephonyManager.listen: 维护监听器列表
- ScrollView.smoothScrollTo: 更新滚动位置

Exception体系扩展:
- 新增15个Exception/Error类 (ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchElementException, AssertionError, OutOfMemoryError, StackOverflowError, NoClassDefFoundError, UnsatisfiedLinkError, LinkageError, VerifyError, AbstractMethodError, IncompatibleClassChangeError, ExceptionInInitializerError)

Math/System/Thread/StringBuilder/Integer增强:
- Math: +20方法 (subtractExact, multiplyExact, toIntExact, floorDiv/floorMod, fma等)
- System: getProperties/setProperties/mapLibraryName/getLogger
- Thread: +10方法 (getUncaughtExceptionHandler, getAllStackTraces, getStackTrace, holdLock等)
- StringBuilder: +7方法 (ensureCapacity, trimToSize, setLength, subSequence等)
- Integer: +8静态方法 (compare, compareUnsigned, divideUnsigned, sum, max, min等)

修复:
- app_fragment.py: 使用java.lang.IllegalStateException替代本地定义
- content_intent.py: Intent.setData/getScheme正确从Uri提取scheme
- view_ext.py: KeyEvent继承view.KeyEvent获取所有KEYCODE常量
- __init__.py: 补全Fragment/KeyEvent/MotionEvent/TrafficStats/RecyclerView等导出

统计: 221模块, 3660类, 30826方法, 180217行
2026-06-24 23:46:36 +00:00

577 lines
18 KiB
Python

"""
Android-pyApi — Android API 全面 Python 翻译
==============================================
方法签名完全对齐 Android SDK,跨平台运行于 Windows/macOS/Linux。
用法:
from android_pyapi import Intent, Context, Uri, Bitmap, View
from android_pyapi.java.io import File, FileInputStream
from android_pyapi.java.util import ArrayList, HashMap
from android_pyapi.org.json import JSONObject, JSONArray
设计原则:
1. 方法名、参数名、返回类型完全对齐 Android SDK
2. 能桌面实现的 → 真实实现 (基于 PIL/sqlite3/socket 等)
3. 无法桌面实现的 → 返回合理默认值或抛出 AndroidOnlyError
4. 所有常量值与 Android SDK 一致
"""
from ._core import (
AndroidOnlyError,
Stub,
android_context,
get_context,
_sdcard_root,
_app_data_dir,
_package_name,
)
# android.* 包
from .android.app import *
from .android.content import *
from .android.content_pm import *
from .android.os import *
from .android.view import *
from .android.view_accessibility import *
from .android.view_animation import *
from .android.view_inputmethod import *
from .android.widget import *
from .android.graphics import *
from .android.graphics_drawable import *
from .android.graphics_pdf import *
from .android.net import *
from .android.net_wifi import *
from .android.media import *
from .android.hardware import *
from .android.hardware_camera2 import *
from .android.hardware_biometrics import *
from .android.location import *
from .android.database import *
from .android.database_sqlite import *
from .android.provider import *
from .android.telephony import *
from .android.bluetooth import *
from .android.bluetooth_le import *
from .android.text import *
from .android.util import *
from .android.preference import *
from .android.webkit import *
from .android.nfc import *
from .android.speech_tts import *
from .android.inputmethod import *
from .android.app_admin import *
from .android.app_backup import *
from .android.app_job import *
from .android.app_people import *
from .android.app_role import *
from .android.app_usage import *
from .android.appwidget import *
from .android.companion import *
from .android.credentials import *
from .android.hardware_display import *
from .android.hardware_fingerprint import *
from .android.hardware_input import *
from .android.hardware_usb import *
from .android.media_audiofx import *
from .android.media_browse import *
from .android.media_midi import *
from .android.media_projection import *
from .android.media_session import *
from .android.media_tv import *
from .android.mtp import *
from .android.opengl import *
from .android.print import *
from .android.renderscript import *
from .android.se import *
from .android.security import *
from .android.service_autofill import *
from .android.service_controls import *
from .android.service_dreams import *
from .android.service_notification import *
from .android.service_quicksettings import *
from .android.service_vr import *
from .android.service_wallpaper import *
from .android.sip import *
from .android.speech import *
from .android.system import *
from .android.telecom import *
from .android.test import *
from .android.transition import *
from .android.uwb import *
from .android.view_autofill import *
from .android.view_textclassifier import *
from .android.view_translation import *
from .android.content_res import *
from .android.accounts import *
from .android.animation import *
from .android.permission import *
from .android.accessibilityservice import *
from .android.os_storage import *
from .android.os_health import *
from .android.os_user import *
from .android.app_slice import *
from .android.app_time import *
from .android.hardware_radio import *
from .android.hardware_consumerir import *
from .android.hardware_thermal import *
from .android.location_ext import *
from .android.net_ssl import *
from .android.net_wifi_aware import *
from .android.text_method import *
from .android.text_style import *
from .android.text_format import *
from .android.text_util import *
from .android.graphics_fonts import *
from .android.graphics_drawable_ext import *
from .android.view_textservice import *
from .android.net_rtp import *
from .android.net_vpn import *
from .android.net_wifi_rtt import *
from .android.net_hotspot2 import *
from .android.app_assist import *
from .android.app_search import *
from .android.gesture import *
from .android.nfc_ext import *
from .android.telephony_mbms import *
from .android.telephony_ims import *
from .android.telephony_euicc import *
from .android.telephony_data import *
from .android.telephony_gsm import *
from .android.telephony_cdma import *
from .android.printservice import *
from .android.service_voice import *
from .android.service_media import *
from .android.inputmethodservice import *
from .android.hardware_camera2_params import *
from .android.graphics_text import *
from .android.graphics_drawable_shapes import *
from .android.graphics_surface import *
from .android.database_ext import *
from .android.drm import *
from .android.app_notification import *
from .android.app_fragment import *
from .android.app_dialog import *
from .android.app_actionbar import *
from .android.app_wallpaper import *
from .android.app_voiceinteractor import *
from .android.content_sync import *
from .android.content_om import *
from .android.managers import *
from .android.net_nsd import *
from .android.net_sip import *
from .android.net_http import *
from .android.os_power import *
from .android.hardware_light import *
from .android.hardware_hdmi import *
from .android.media_effect import *
from .android.media_face import *
from .android.media_async import *
from .android.media_image import *
from .android.media_capture import *
from .android.view_ext import *
from .android.widget_ext import *
from .android.view_accessibility_ext import *
from .android.view_dragndrop import *
from .android.view_gesture import *
from .android.view_haptic import *
from .android.webkit_ext import *
from .android.location_geofence import *
from .android.provider_contacts import *
from .android.provider_calendar import *
from .android.provider_settings import *
from .android.media_tv_ext import *
from .android.media_audio import *
from .android.media_remoteblob import *
from .android.net_ext import *
from .android.net_ethernet import *
from .android.hardware_sensor_ext import *
from .android.hardware_location import *
from .android.hardware_serial import *
from .android.app_tasks import *
from .android.companion_ext import *
from .android.view_animator import *
from .android.view_window import *
from .android.widget_adapter import *
from .android.content_intent import *
from .android.gesture_ext import *
# java.* 包
from .java.io import *
from .java.net import *
from .java.util import *
from .java.util_regex import *
from .java.util_zip import *
from .java.util_concurrent import *
from .java.lang import *
from .java.math import *
from .java.text import *
from .java.time import *
from .java.nio import *
from .java.nio_file import *
from .java.security import *
from .java.crypto import *
from .java.lang_ref import *
from .java.lang_reflect import *
from .java.lang_annotation import *
from .java.nio_channels import *
from .java.nio_charset import *
from .java.security_cert import *
from .java.security_spec import *
from .java.sql import *
from .java.beans import *
from .java.rmi import *
from .java.util_function import *
from .java.util_logging import *
from .java.util_stream import *
from .java.util_prefs import *
from .java.lang_invoke import *
from .java.lang_management import *
from .java.nio_byteorder import *
from .java.io_ext import *
from .java.io_file import *
from .java.util_concurrent_atomic import *
from .java.util_concurrent_locks import *
# javax.* 包
from .javax.net import *
from .javax.crypto import *
from .javax.security import *
from .javax.sql import *
# org.* 包
from .org.json import *
from .org.w3c_dom import *
from .org.xml_sax import *
from .org.xml_pull import *
from .org.apache.http import *
# dalvik.* 包
from .dalvik.system import *
# Base64 (标准 Android API)
import base64 as _base64
class Base64:
DEFAULT = 0
NO_PADDING = 1
NO_WRAP = 2
CRLF = 4
URL_SAFE = 8
NO_CLOSE = 16
@staticmethod
def encodeToString(input_data, flags=0):
if isinstance(input_data, str):
input_data = input_data.encode('utf-8')
return _base64.b64encode(input_data).decode('ascii')
@staticmethod
def decode(str_val, flags=0):
return _base64.b64decode(str_val)
@staticmethod
def encode(input_data, flags=0):
if isinstance(input_data, str):
input_data = input_data.encode('utf-8')
return _base64.b64encode(input_data)
# Scanner (java.util)
class Scanner:
def __init__(self, source):
if isinstance(source, str):
self._source = source
else:
self._source = str(source)
self._pos = 0
def next(self):
while self._pos < len(self._source) and self._source[self._pos].isspace():
self._pos += 1
start = self._pos
while self._pos < len(self._source) and not self._source[self._pos].isspace():
self._pos += 1
if start == self._pos:
raise Exception("NoSuchElementException")
return self._source[start:self._pos]
def hasNext(self):
pos = self._pos
while pos < len(self._source) and self._source[pos].isspace():
pos += 1
return pos < len(self._source)
def nextInt(self):
return int(self.next())
def close(self):
pass
# Timer (java.util)
class Timer:
def __init__(self, name=None, daemon=False):
import threading
self._thread = None
self._tasks = []
def schedule(self, task, delay=None, period=None):
import threading
if delay is None:
self._run_once(task)
elif period is None:
self._run_delayed(task, delay)
else:
self._run_periodic(task, delay, period)
def _run_once(self, task):
t = threading.Thread(target=task.run)
t.daemon = True
self._tasks.append(t)
t.start()
def _run_delayed(self, task, delay_ms):
import threading
def _run():
import time
time.sleep(delay_ms / 1000.0)
task.run()
t = threading.Thread(target=_run)
t.daemon = True
self._tasks.append(t)
t.start()
def _run_periodic(self, task, delay_ms, period_ms):
import threading
def _run():
import time
time.sleep(delay_ms / 1000.0)
while True:
task.run()
time.sleep(period_ms / 1000.0)
t = threading.Thread(target=_run)
t.daemon = True
self._tasks.append(t)
t.start()
def cancel(self):
pass
def purge(self):
return 0
class TimerTask:
def __init__(self):
self._cancelled = False
def run(self):
pass
def cancel(self):
self._cancelled = True
def scheduledExecutionTime(self):
return 0
__version__ = "1.0.0"
__all__ = [
# android — 核心
"AccessibilityNodeInfo", "AccessibilityService",
"AccessibilityServiceInfo",
"Account", "AccountManager",
"Activity", "ActivityManager",
"Fragment", "FragmentManager", "FragmentTransaction",
"Dialog", "AlertDialog", "ProgressDialog",
"DatePickerDialog", "TimePickerDialog",
"Service", "Application",
"PendingIntent", "ComponentName", "AlarmManager",
"NotificationChannel", "NotificationChannelGroup",
"NotificationCompat", "TaskStackBuilder",
"AlphaAnimation",
"Animation",
"Animator", "ValueAnimator", "ObjectAnimator", "AnimatorSet",
"AppWidgetManager", "AppWidgetProvider", "AppWidgetProviderInfo",
"AssistManager", "AssistStructure",
"AudioManager",
"AutofillManager", "AutofillValue",
"BackupAgent", "BackupManager",
"Base64",
"BatteryManager",
"BiometricPrompt",
"Bitmap", "BitmapDrawable", "BitmapFactory",
"BluetoothAdapter", "BluetoothDevice",
"BroadcastReceiver",
"Build",
"Bundle",
"Button",
"CalendarContract",
"Call",
"CameraManager",
"Canvas",
"CheckBox",
"Color",
"CompanionDeviceManager",
"ConnectivityManager",
"ConsumerIrManager",
"ContentResolver",
"ContentValues",
"ContactsContract",
"Context",
"CredentialManager",
"Cursor",
"DevicePolicyManager",
"DisplayManager",
"Drawable",
"EditText",
"Environment",
"FingerprintManager",
"Geocoder",
"Gesture", "GestureOverlayView", "GestureLibrary",
"Handler",
"Html",
"ImageView",
"InputDevice",
"KeyEvent", "MotionEvent",
"InputManager",
"InputMethodManager",
"Intent",
"IntentFilter",
"JobInfo", "JobScheduler", "JobService",
"KeyChain",
"ListView",
"Location", "LocationManager",
"Log",
"Looper",
"Matrix",
"MediaBrowser", "MediaController",
"MediaPlayer",
"MediaProjectionManager",
"MediaRecorder",
"MediaSession",
"MediaStore",
"Message",
"MidiDevice", "MidiManager",
"MtpDevice",
"NfcAdapter", "NdefMessage", "NdefRecord", "Tag",
"NetworkInfo",
"Os", "OsConstants",
"PackageInfo", "PackageManager",
"Paint",
"PdfRenderer",
"PeopleManager",
"PermissionManager",
"PowerManager",
"PrintAttributes", "PrintDocumentAdapter", "PrintManager",
"ProgressBar",
"RadioManager", "RadioTuner",
"Rect", "RectF",
"RecyclerView",
"Resources", "AssetManager",
"RoleManager",
"ScrollView",
"SearchManager", "SearchableInfo",
"SensorManager",
"Settings",
"SharedPreferences",
"Slice", "SliceManager", "SliceProvider",
"SmsManager",
"SpannableString",
"SpeechRecognizer",
"Spinner",
"SQLiteDatabase", "SQLiteOpenHelper",
"StorageManager", "StorageVolume",
"StructStat",
"Switch",
"TelecomManager",
"TelephonyManager",
"TextClassifier",
"TextToSpeech",
"TextUtils",
"TextView",
"ThermalManager",
"TimeManager",
"Toast",
"TrafficStats",
"TranslateAnimation",
"TranslationManager",
"TvInputManager",
"Typeface",
"TypedValue",
"Uri",
"UsageStatsManager",
"UsbDevice", "UsbManager",
"UserManager", "UserHandle",
"UwbManager",
"View", "ViewGroup",
"VirtualDisplay",
"VpnManager", "VpnService",
"WebView",
"WifiAwareManager",
"WifiManager",
"WifiRttManager",
# java
"File", "FileInputStream", "FileOutputStream",
"BufferedReader", "BufferedWriter",
"InputStreamReader", "OutputStreamWriter",
"URL", "HttpURLConnection", "Socket", "ServerSocket",
"ArrayList", "HashMap", "HashSet", "LinkedList",
"Collections", "Arrays", "Calendar", "Date", "Random",
"UUID", "Scanner", "Timer", "TimerTask",
"Pattern", "Matcher",
"ZipFile", "GZIPInputStream", "GZIPOutputStream",
"ExecutorService", "Executors", "Future", "Callable",
"String", "StringBuilder", "StringBuffer",
"Integer", "Math", "System", "Thread",
"BigInteger", "BigDecimal",
# Java Exception 体系
"Throwable", "Exception", "RuntimeException", "Error",
"NullPointerException", "IllegalArgumentException", "IllegalStateException",
"IndexOutOfBoundsException", "ArrayIndexOutOfBoundsException",
"StringIndexOutOfBoundsException", "ClassCastException",
"UnsupportedOperationException", "ArithmeticException",
"NumberFormatException", "SecurityException",
"ConcurrentModificationException", "NegativeArraySizeException",
"NoSuchFieldException", "NoSuchMethodException", "InterruptedException",
"CloneNotSupportedException", "IllegalMonitorStateException",
"IllegalThreadStateException", "EnumConstantNotPresentException",
"TypeNotPresentException",
# Java Exception 体系 (扩展)
"ClassNotFoundException", "IllegalAccessException",
"InstantiationException", "InvocationTargetException",
"NoSuchElementException", "AssertionError",
"OutOfMemoryError", "StackOverflowError", "NoClassDefFoundError",
"UnsatisfiedLinkError", "LinkageError", "VerifyError",
"AbstractMethodError", "IncompatibleClassChangeError",
"ExceptionInInitializerError",
"SimpleDateFormat", "DecimalFormat",
"LocalDateTime", "LocalDate", "LocalTime", "Instant", "Duration", "Period",
"ChronoUnit", "ChronoField", "DayOfWeek", "Month", "ZoneId", "ZoneOffset",
"DateTimeFormatter",
"ByteBuffer", "Files", "Path", "Paths",
"MessageDigest", "SecureRandom",
"Cipher", "Mac", "KeyGenerator",
"SecretKey", "SecretKeySpec",
"Reference", "SoftReference", "WeakReference", "PhantomReference",
"Field", "Method", "Constructor", "Proxy", "Modifier",
"Annotation", "Retention", "Target", "RetentionPolicy", "ElementType",
"Channel", "Selector", "SelectionKey", "SocketChannel", "ServerSocketChannel",
"FileChannel", "DatagramChannel",
"Charset", "CharsetEncoder", "CharsetDecoder", "StandardCharsets",
"CoderResult",
# javax
"SSLSocketFactory", "SSLServerSocketFactory",
"SSLSocket", "SSLServerSocket", "HttpsURLConnection",
"TrustManager", "X509TrustManager", "KeyManager", "X509KeyManager",
"Cipher", "KeyGenerator", "Mac", "SecretKey", "SecretKeySpec",
"Subject", "Principal", "Policy",
"DataSource", "RowSet", "CachedRowSet", "RowSetListener",
# org
"JSONObject", "JSONArray", "JSONException",
"Document", "Node", "Element", "Attr", "Text", "NodeList",
"XMLReader", "ContentHandler", "InputSource", "SAXException",
"XmlPullParser", "XmlSerializer", "XmlPullParserFactory",
"HttpResponse", "HttpEntity", "HttpClient", "DefaultHttpClient",
"HttpGet", "HttpPost", "HttpPut", "HttpDelete",
# dalvik
"DexClassLoader", "PathClassLoader", "DexFile",
]