Java Code Examples for android.net.wifi.WifiManager#createWifiLock()

The following examples show how to use android.net.wifi.WifiManager#createWifiLock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LockManager.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public LockManager(Context context) {
  PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
  fullLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "signal:full");
  partialLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "signal:partial");
  proximityLock = new ProximityLock(pm);

  WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "signal:wifi");

  fullLock.setReferenceCounted(false);
  partialLock.setReferenceCounted(false);
  wifiLock.setReferenceCounted(false);

  accelerometerListener = new AccelerometerListener(context, new AccelerometerListener.OrientationListener() {
    @Override
    public void orientationChanged(int newOrientation) {
      orientation = newOrientation;
      Log.d(TAG, "Orentation Update: " + newOrientation);
      updateInCallLockState();
    }
  });

  wifiLockEnforced = isWifiPowerActiveModeEnabled(context);
}
 
Example 2
Source File: ReplicationService.java    From sync-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifiManager != null) {
        mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF,
            "ReplicationService");
    }

    // Create a background priority thread to so we don't block the process's main thread.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler.
    Looper serviceLooper = thread.getLooper();
    mServiceHandler = getHandler(serviceLooper);
}
 
Example 3
Source File: Downloader.java    From AntennaPodSP with MIT License 6 votes vote down vote up
public final Downloader call() {
    WifiManager wifiManager = (WifiManager) PodcastApp.getInstance().getSystemService(Context.WIFI_SERVICE);
    WifiManager.WifiLock wifiLock = null;
    if (wifiManager != null) {
        wifiLock = wifiManager.createWifiLock(TAG);
        wifiLock.acquire();
    }

    download();

    if (wifiLock != null) {
        wifiLock.release();
    }

    if (result == null) {
        throw new IllegalStateException(
                "Downloader hasn't created DownloadStatus object");
    }
    finished = true;
    return this;
}
 
Example 4
Source File: NetworkLocationProvider.java    From your-local-weather with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mTelephonyManager = ((TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE));
    alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

    try {
        mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "SCAN_LOCK");
        if (!mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    } catch (UnsupportedOperationException uoe) {
        appendLog(getBaseContext(), TAG,
                "Unable to acquire wifi lock.", uoe);
    }
    registerReceiver(mReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
 
Example 5
Source File: NodeMainExecutorService.java    From rosjava_android_template with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
  handler = new Handler();
  PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
  wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  wakeLock.acquire();
  int wifiLockType = WifiManager.WIFI_MODE_FULL;
  try {
    wifiLockType = WifiManager.class.getField("WIFI_MODE_FULL_HIGH_PERF").getInt(null);
  } catch (Exception e) {
    // We must be running on a pre-Honeycomb device.
    Log.w(TAG, "Unable to acquire high performance wifi lock.");
  }
  WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  wifiLock = wifiManager.createWifiLock(wifiLockType, TAG);
  wifiLock.acquire();
}
 
Example 6
Source File: AcquireWifiLockService.java    From Xndroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    sXndroidFile = getFilesDir().getAbsolutePath() + "/xndroid_files";
    sFqHome = sXndroidFile + "/fqrouter";
    if(LogUtils.sGetDefaultLog() == null){
        LogUtils.sSetDefaultLog(new LogUtils(sXndroidFile+"/log/java_wifi.log"));
    }
    LogUtils.i("AcquireWifiLockService onCreate");
    super.onCreate();
    try {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (null == wifiLock) {
            wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "fqrouter wifi hotspot");
        }
        wifiLock.acquire();
        LogUtils.i("acquired wifi lock");
    } catch (Exception e) {
        LogUtils.e("failed to acquire wifi lock", e);
    }
}
 
Example 7
Source File: Util.java    From Popeens-DSub with GNU General Public License v3.0 5 votes vote down vote up
public static WifiManager.WifiLock createWifiLock(Context context, String tag) {
	WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	int lockType = WifiManager.WIFI_MODE_FULL;
	if (Build.VERSION.SDK_INT >= 12) {
		lockType = 3;
	}
	return wm.createWifiLock(lockType, tag);
}
 
Example 8
Source File: FieldTripClientsService.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {

    if (wakeLock == null && wifiLock == null) {
        updater = new Updater(this);
        updater.start();
        updater.update = false;
        final int port = intent.getIntExtra("port", 1972);

        // Get Wakelocks
        final PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, C.WAKELOCKTAG);
        wakeLock.acquire();

        final WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiLock = wifiMan.createWifiLock(C.WAKELOCKTAGWIFI);
        wifiLock.acquire();

        // Create Foreground Notification
        // Create notification text
        final Resources res = getResources();
        final String notification_text = res.getString(R.string.notification_text);
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable
                .ic_launcher).setContentTitle(res.getString(R.string.notification_title)).setContentText
                (notification_text);

        // Turn this service into a foreground service
        startForeground(1, mBuilder.build());
        Log.i(TAG, "Fieldtrip Clients Service moved to foreground.");
    }

    createAllThreadsAndBroadcastInfo();

    if (threads != null) {
        this.registerReceiver(mMessageReceiver, intentFilter);
    }

    return START_NOT_STICKY;
}
 
Example 9
Source File: UsbIpService.java    From USBIPServerForAndroid with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("UseSparseArrays")
@Override
public void onCreate() {
	super.onCreate();
	
	usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);		
	connections = new SparseArray<AttachedDeviceContext>();
	permission = new SparseArray<Boolean>();
	socketMap = new HashMap<Socket, AttachedDeviceContext>();
	
	usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
	IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
	registerReceiver(usbReceiver, filter);
	
	PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	
	cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "USB/IP Service");
	cpuWakeLock.acquire();
	
	wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "USB/IP Service");
	wifiLock.acquire();
	
	server = new UsbIpServer();
	server.start(this);
	
	updateNotification();
}
 
Example 10
Source File: LocalPlayback.java    From klingar with Apache License 2.0 5 votes vote down vote up
LocalPlayback(Context context, MusicController musicController, AudioManager audioManager,
              WifiManager wifiManager, Call.Factory callFactory) {
  this.context = context;
  this.musicController = musicController;
  this.audioManager = audioManager;
  this.wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "klingar");
  String agent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name));
  this.mediaSourceFactory = new ProgressiveMediaSource.Factory(new DefaultDataSourceFactory(
      context, null, new OkHttpDataSourceFactory(callFactory, agent)));
}
 
Example 11
Source File: WifiAdmin.java    From cordova-plugin-wifi with MIT License 5 votes vote down vote up
private PluginResult executeEnableWifiLock(JSONArray inputs, CallbackContext callbackContext) {
  	Log.w(LOGTAG, "executeEnableWifiLock");

boolean toEnable = true;
try {
	toEnable = inputs.getBoolean( 0 );
} catch (JSONException e) {
      Log.w(LOGTAG, String.format("Got JSON Exception: %s", e.getMessage()));
      return new PluginResult(Status.JSON_EXCEPTION);
}

Context context = cordova.getActivity().getApplicationContext();
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

if(wifiLock == null) {
	wifiLock = wifiManager.createWifiLock("Test");
}

if(wifiLock != null) {
	if(toEnable) {
		wifiLock.acquire();
	} else {
        if(wifiLock.isHeld()) {
        	wifiLock.release();
        }
	}
}

callbackContext.success();

  	return null;
  }
 
Example 12
Source File: RMBTService.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate()
{
    Log.d(DEBUG_TAG, "created");
    super.onCreate();
    
    handler = new Handler();
    
    // initialise the locks
    loopMode = ConfigHelper.isLoopMode(this);
    
    // initialise the locks
    wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "RMBTWifiLock");
    wakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE)).newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK, "RMBTWakeLock");
    
    // mNetworkStateIntentReceiver = new BroadcastReceiver() {
    // @Override
    // public void onReceive(Context context, Intent intent) {
    // if
    // (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
    // {
    //
    // final boolean connected = !
    // intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
    // false);
    // if (! connected)
    // stopTest();
    // }
    // }
    // };
    // final IntentFilter networkStateChangedFilter = new IntentFilter();
    // networkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    //
    // registerReceiver(mNetworkStateIntentReceiver,
    // networkStateChangedFilter);
}
 
Example 13
Source File: CommonDeviceLocks.java    From test-butler with Apache License 2.0 5 votes vote down vote up
/**
 * Create locks for the given application context.
 * @param context The application context
 */
void acquire(@NonNull Context context) {
    // Acquire a WifiLock to prevent wifi from turning off and breaking tests
    // NOTE: holding a WifiLock does NOT override a call to setWifiEnabled(false)
    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ButlerWifiLock");
    } else {
        wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "ButlerWifiLock");
    }
    wifiLock.acquire();

    // Acquire a keyguard lock to prevent the lock screen from randomly appearing and breaking tests
    // KeyguardManager has been restricted in Q, so we don't use to avoid breaking all test runs on Q emulators
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
        KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);
        keyguardLock = keyguardManager.newKeyguardLock("ButlerKeyguardLock");
        keyguardLock.disableKeyguard();
    }

    // Acquire a wake lock to prevent the cpu from going to sleep and breaking tests
    PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.ON_AFTER_RELEASE, "TestButlerApp:WakeLock");
    wakeLock.acquire();
}
 
Example 14
Source File: HostActivity.java    From ExoPlayer-Offline with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
  Context appContext = getApplicationContext();
  WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
  wifiLock = wifiManager.createWifiLock(getWifiLockMode(), TAG);
  wifiLock.acquire();
  PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
  wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  wakeLock.acquire();
  super.onStart();
}
 
Example 15
Source File: ShellService.java    From RemoteAdbShell with Apache License 2.0 5 votes vote down vote up
private synchronized void acquireWakeLocks() {
	if (wlanLock == null) {
		WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		wlanLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Remote ADB Shell");
	}
	if (wakeLock == null) {
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Remote ADB Shell");
	}
	wakeLock.acquire();
	wlanLock.acquire();
}
 
Example 16
Source File: Badservice.java    From android_emulator_hacks with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Stresstesting has a habbit of turning off the wifi....
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "hack_wifilock");
    wifiLock.acquire();

    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    keyguardLock = keyguardManager.newKeyguardLock("hack_activity");
    keyguardLock.disableKeyguard();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.ON_AFTER_RELEASE, "hack_wakelock");
    wakeLock.acquire();
    Log.d(HackActivity.TAG, "Badservice running, will hold wifi lock, wakelock and keyguard lock");
    audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    SettingsContentObserver observer = new SettingsContentObserver(new Handler());
    this.getApplicationContext().getContentResolver().registerContentObserver(
            android.provider.Settings.System.CONTENT_URI, true, observer);

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.d(HackActivity.TAG, "Badservice shutting down");
            wifiLock.release();
            wakeLock.release();
            keyguardLock.reenableKeyguard();
            stopSelf();
        }
    }, 1000 * 60 * 60);
    
    muteVolume();
}
 
Example 17
Source File: PjSipService.java    From react-native-pjsip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (!mInitialized) {
        if (intent != null && intent.hasExtra("service")) {
            mServiceConfiguration = ServiceConfigurationDTO.fromMap((Map) intent.getSerializableExtra("service"));
        }

        mWorkerThread = new HandlerThread(getClass().getSimpleName(), Process.THREAD_PRIORITY_FOREGROUND);
        mWorkerThread.setPriority(Thread.MAX_PRIORITY);
        mWorkerThread.start();
        mHandler = new Handler(mWorkerThread.getLooper());
        mEmitter = new PjSipBroadcastEmiter(this);
        mAudioManager = (AudioManager) getApplicationContext().getSystemService(AUDIO_SERVICE);
        mPowerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE);
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mWifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, this.getPackageName()+"-wifi-call-lock");
        mWifiLock.setReferenceCounted(false);
        mTelephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        mGSMIdle = mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE;

        IntentFilter phoneStateFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        registerReceiver(mPhoneStateChangedReceiver, phoneStateFilter);

        mInitialized = true;

        job(new Runnable() {
            @Override
            public void run() {
                load();
            }
        });
    }

    if (intent != null) {
        job(new Runnable() {
            @Override
            public void run() {
                handle(intent);
            }
        });
    }

    return START_NOT_STICKY;
}
 
Example 18
Source File: FieldTripServerService.java    From buffer_bci with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    Log.i(TAG, "Buffer Service Running");
    // If no buffer is running.
    if (buffer == null) {

        final int port = intent.getIntExtra("port", 1972);
        // Get Wakelocks

        final PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                C.WAKELOCKTAG);
        wakeLock.acquire();

        final WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiLock = wifiMan.createWifiLock(C.WAKELOCKTAGWIFI);
        wifiLock.acquire();

        // Create Foreground Notification

        // Get the currently used ip-address
        final WifiInfo wifiInf = wifiMan.getConnectionInfo();
        final int ipAddress = wifiInf.getIpAddress();
        final String ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d",
                ipAddress & 0xff, ipAddress >> 8 & 0xff,
                ipAddress >> 16 & 0xff, ipAddress >> 24 & 0xff);

        // Create notification text
        final Resources res = getResources();
        final String notification_text = String.format(
                res.getString(R.string.notification_text), ip + ":" + port);

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(res.getString(R.string.notification_title))
                .setContentText(notification_text);

        // Create a buffer and start it.
        if (isExternalStorageWritable()) {
            Log.i(TAG, "External storage is writable");
            long time = Calendar.getInstance().getTimeInMillis();
            File file = getStorageDir("buffer_dump_" + String.valueOf(time));
            buffer = new BufferServer(port, intent.getIntExtra("nSamples", 100),
                    intent.getIntExtra("nEvents", 100), file);
        } else {
            Log.i(TAG, "External storage is sadly not writable");
            Log.w(TAG, "Storage is not writable. I am not saving the data.");
            buffer = new BufferServer(port, intent.getIntExtra("nSamples", 100),
                    intent.getIntExtra("nEvents", 100));
        }
        monitor = new BufferMonitor(this, ip + ":" + port,
                System.currentTimeMillis());
        buffer.addMonitor(monitor);

        // Start the buffer and Monitor
        buffer.start();
        Log.i(TAG, "1");
        monitor.start();
        Log.i(TAG, "Buffer thread started.");

        // Turn this service into a foreground service
        startForeground(1, mBuilder.build());
        Log.i(TAG, "Fieldtrip Buffer Service moved to foreground.");


        if (buffer != null) {
            this.registerReceiver(mMessageReceiver, intentFilter);
            Log.i(TAG, "Registered receiver with buffer:" + buffer.getName());
        }


    }
    return START_NOT_STICKY;
}
 
Example 19
Source File: BufferClientsService.java    From buffer_bci with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    Log.d(TAG, "Buffer Clients Service - starting.");
    //android.os.Debug.waitForDebugger();
    if (wakeLock == null && wifiLock == null) {
        updater = new Updater(this);
        updater.start();
        updater.stopUpdating();
        final int port = intent.getIntExtra("port", 1972);

        // Get Wakelocks
        final PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, C.WAKELOCKTAG);
        wakeLock.acquire();

        final WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiLock = wifiMan.createWifiLock(C.WAKELOCKTAGWIFI);
        wifiLock.acquire();
    }

    createAllThreads();
    broadcastAllThreadInfo();

    if (threads != null) {
        this.registerReceiver(mMessageReceiver, intentFilter);
    }

    // Create Foreground Notification
    // Create notification text
    final Resources res = getResources();
    String notification_text = String.format(res.getString(R.string.clients_notification_text),threadInfos.size());
    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(res.getString(R.string.clients_notification_title)).setContentText(notification_text);

    // Turn this service into a foreground service
    startForeground(C.CLIENTS_SERVICE_NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Buffer Clients Service moved to foreground.");
    Log.d(TAG, "Buffer Clients Service - started.");

    // start the status update thread sending info.
    updater.startUpdating();
    return START_NOT_STICKY;
}
 
Example 20
Source File: BufferServerService.java    From buffer_bci with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    //android.os.Debug.waitForDebugger();
    // If no buffer is running.
    if (wakeLock==null && wifiLock==null ) { // Get Wakelocks

        final PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                C.WAKELOCKTAG);
        wakeLock.acquire();

        final WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiLock = wifiMan.createWifiLock(C.WAKELOCKTAGWIFI);
        wifiLock.acquire();

    }
    // Get the currently used ip-address
    final int port = intent.getIntExtra("port", 1972);
    final WifiInfo wifiInf = ((WifiManager) getSystemService(WIFI_SERVICE)).getConnectionInfo();
    final int ipAddress = wifiInf.getIpAddress();
    final String ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d",
            ipAddress & 0xff, ipAddress >> 8 & 0xff,
            ipAddress >> 16 & 0xff, ipAddress >> 24 & 0xff);
    String saveDirName="";

    if ( buffer==null ) {
        final int sampleBuffSize = intent.getIntExtra("nSamples", 100);
        final int eventBuffSize = intent.getIntExtra("nEvents", 100);
        // Create a buffer and start it.

        if (isExternalStorageWritable()) {
            Log.i(TAG, "External storage is writable");
            Date now = new Date();
            String session = (new java.text.SimpleDateFormat("yyMMdd", Locale.US)).format(now);
            String block = (new java.text.SimpleDateFormat("HHmm", Locale.US)).format(now);
            File savedir = new File(getExternalFilesDir(null),
                    "raw_buffer"+ "/" + session + "/" + block);
            savedir.mkdirs();
            if ( !savedir.canWrite()) {
                Log.e(TAG, "Save session directory not created :" + savedir.getPath());
            } else {
                saveDirName=savedir.getPath();
                Log.i(TAG, "Saving to directory: " + saveDirName);
                buffer = new BufferServer(port, sampleBuffSize, eventBuffSize, savedir);
            }
        }

        if (buffer == null) {
            saveDirName="";
            Log.i(TAG, "External storage is sadly not writable");
            Log.w(TAG, "Storage is not writable. I am not saving the data.");
            buffer = new BufferServer(port, sampleBuffSize, eventBuffSize);
        }
        monitor = new BufferMonitor(this, ip + ":" + port, System.currentTimeMillis());
        buffer.addMonitor(monitor);

        // Start the buffer and Monitor
        buffer.start();
        Log.i(TAG, "Buffer started");
        monitor.start();
        Log.i(TAG, "Buffer monitor started.");
    }


    if (buffer != null) {
        this.registerReceiver(mMessageReceiver, intentFilter);
        Log.i(TAG, "Registered receiver with buffer:" + buffer.getName());
    }

    Log.i(TAG, "Buffer Service Running");

    // Create notification text
    final Resources res = getResources();
    final String notification_text;
    if ( saveDirName == null ) {
        notification_text =
                String.format(res.getString(R.string.server_notification_text_host), ip + ":" + port)
                        + "      " + res.getString(R.string.server_notification_text_nosavedir);
    } else {
        notification_text =
                   String.format(res.getString(R.string.server_notification_text_host), ip + ":" + port)
                        + "      " + String.format(res.getString(R.string.server_notification_text_savedir), saveDirName);
    }

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(res.getString(R.string.server_notification_title))
            .setContentText(notification_text);

    // Turn this service into a foreground service
    startForeground(C.SERVER_SERVICE_NOTIFICATION_ID, mBuilder.build());
    Log.i(TAG, "Buffer Server Service moved to foreground.");

    return START_NOT_STICKY;
}