summaryrefslogtreecommitdiffstats
path: root/base/android/jni_android.cc
blob: 9c655acd7e863a6304deb30186dc1c7cc59a443f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/android/jni_android.h"

#include "base/logging.h"

namespace {
JavaVM* g_jvm = 0;
jobject g_application_context = NULL;
}

namespace base {
namespace android {

JNIEnv* AttachCurrentThread() {
  if (!g_jvm)
    return NULL;

  JNIEnv* env = NULL;
  jint ret = g_jvm->AttachCurrentThread(&env, NULL);
  DCHECK_EQ(ret, JNI_OK);
  return env;
}

void DetachFromVM() {
  // Ignore the return value, if the thread is not attached, DetachCurrentThread
  // will fail. But it is ok as the native thread may never be attached.
  if (g_jvm)
    g_jvm->DetachCurrentThread();
}

void InitVM(JavaVM* vm) {
  DCHECK(!g_jvm);
  g_jvm = vm;
}

void InitApplicationContext(jobject context) {
  DCHECK(!g_application_context);
  g_application_context = context;
}

jobject GetApplicationContext() {
  DCHECK(g_application_context);
  return g_application_context;
}

jmethodID GetMethodID(JNIEnv* env,
                      jclass clazz,
                      const char* const method,
                      const char* const jni_signature) {
  jmethodID id = env->GetMethodID(clazz, method, jni_signature);
  DCHECK(id) << method;
  CheckException(env);
  return id;
}

bool CheckException(JNIEnv* env) {
  if (env->ExceptionCheck() == JNI_FALSE)
    return false;
  env->ExceptionDescribe();
  env->ExceptionClear();
  return true;
}

}  // namespace android
}  // namespace base