Android/Context: look up methods once during startup

This commit is contained in:
Max Kellermann 2022-08-18 15:12:18 +02:00
parent 1f4df2a64d
commit b90e32fe4e
3 changed files with 29 additions and 18 deletions

View File

@ -614,9 +614,12 @@ Java_org_musicpd_Bridge_run(JNIEnv *env, jclass, jobject _context, jobject _logL
Java::Init(env);
Java::Object::Initialise(env);
Java::File::Initialise(env);
Environment::Initialise(env);
AtScopeExit(env) { Environment::Deinitialise(env); };
Context::Initialise(env);
context = new Context(env, _context);
AtScopeExit() { delete context; };

View File

@ -26,19 +26,31 @@
#include "AudioManager.hxx"
static jmethodID getExternalFilesDir_method,
getCacheDir_method,
getSystemService_method;
void
Context::Initialise(JNIEnv *env) noexcept
{
Java::Class cls{env, "android/content/Context"};
getExternalFilesDir_method = env->GetMethodID(cls, "getExternalFilesDir",
"(Ljava/lang/String;)Ljava/io/File;");
getCacheDir_method = env->GetMethodID(cls, "getCacheDir",
"()Ljava/io/File;");
getSystemService_method = env->GetMethodID(cls, "getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;");
}
AllocatedPath
Context::GetExternalFilesDir(JNIEnv *env, const char *_type) noexcept
{
assert(_type != nullptr);
Java::Class cls{env, env->GetObjectClass(Get())};
jmethodID method = env->GetMethodID(cls, "getExternalFilesDir",
"(Ljava/lang/String;)Ljava/io/File;");
assert(method);
Java::String type{env, _type};
jobject file = env->CallObjectMethod(Get(), method, type.Get());
jobject file = env->CallObjectMethod(Get(), getExternalFilesDir_method, type.Get());
if (Java::DiscardException(env) || file == nullptr)
return nullptr;
@ -50,12 +62,7 @@ Context::GetCacheDir(JNIEnv *env) const noexcept
{
assert(env != nullptr);
Java::Class cls(env, env->GetObjectClass(Get()));
jmethodID method = env->GetMethodID(cls, "getCacheDir",
"()Ljava/io/File;");
assert(method);
jobject file = env->CallObjectMethod(Get(), method);
jobject file = env->CallObjectMethod(Get(), getCacheDir_method);
if (Java::DiscardException(env) || file == nullptr)
return nullptr;
@ -67,13 +74,8 @@ Context::GetAudioManager(JNIEnv *env) noexcept
{
assert(env != nullptr);
Java::Class cls(env, env->GetObjectClass(Get()));
jmethodID method = env->GetMethodID(cls, "getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;");
assert(method);
Java::String name(env, "audio");
jobject am = env->CallObjectMethod(Get(), method, name.Get());
jobject am = env->CallObjectMethod(Get(), getSystemService_method, name.Get());
if (Java::DiscardException(env) || am == nullptr)
return nullptr;

View File

@ -27,6 +27,12 @@ class AudioManager;
class Context : public Java::GlobalObject {
public:
/**
* Global initialisation. Looks up the methods of the
* Context Java class.
*/
static void Initialise(JNIEnv *env) noexcept;
Context(JNIEnv *env, jobject obj) noexcept
:Java::GlobalObject(env, obj) {}