Guest User

Untitled

a guest
Jun 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. #include <mach/mach_port.h>
  6. #include <mach/mach_interface.h>
  7. #include <mach/mach_init.h>
  8.  
  9. #include <IOKit/pwr_mgt/IOPMLib.h>
  10. #include <IOKit/IOMessage.h>
  11.  
  12. #include <jni.h>
  13.  
  14. struct MySleepContext {
  15.     io_connect_t root_port; // the Root Power Domain IOService;
  16.     jobject callback; // the Java callback
  17.     JNIEnv * env; // the Java environment
  18. };
  19.  
  20. void MySleepCallBack(void * pointer, io_service_t service, natural_t messageType, void * messageArgument) {
  21.     struct MySleepContext * context = pointer;
  22.     jclass callbackClass = (*context->env)->GetObjectClass(context->env, context->callback);
  23.     jmethodID mid = (*context->env)->GetMethodID(context->env, callbackClass, "allowIdleSleep", "()Z");
  24.     jboolean allow = (*context->env)->CallBooleanMethod(context->env, context->callback, mid);
  25.  
  26.     switch (messageType) {
  27.         case kIOMessageCanSystemSleep:
  28.             if (allow == JNI_TRUE) {
  29.                 IOAllowPowerChange(context->root_port, (long) messageArgument);
  30.             } else {
  31.                 IOCancelPowerChange(context->root_port, (long) messageArgument);
  32.             }
  33.             break;
  34.         case kIOMessageSystemWillSleep:
  35.             IOAllowPowerChange(context->root_port, (long) messageArgument);
  36.             break;
  37.         default:
  38.             break;
  39.     }
  40. }
  41.  
  42. JNIEXPORT void JNICALL KeepAwakeNative_keepAwakeNative (JNIEnv * env, jobject obj, jobject callback) {
  43.     IONotificationPortRef notifyPortRef;
  44.     io_object_t notifierObject;
  45.  
  46.     struct MySleepContext * context;
  47.     context->callback = callback;
  48.     context->env = env;
  49.  
  50.     context->root_port = IORegisterForSystemPower(context, &notifyPortRef, MySleepCallBack, &notifierObject);
  51.     CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);
  52.    
  53.     // blocks
  54.     CFRunLoopRun();
  55. }
Add Comment
Please, Sign In to add comment