I want to switch on the display (and do other stuff like showing some information) of my android tablet via an external command. My solution was to start a webserver on the tablet, open a webpage and then the display should be switched on.
This works if I start the app but after a while the webserver does not respond anymore. I can see in my wifi router that the wifi connection is still OK. If I close and start the app again it works again for a while. It looks like my service is going to be killed by android.
I started the server as a service from the MainActivity (onCreate) with startService(new Intent(this, ServerService.class));
.
ServerService extends Service. In onCreate I did the following:
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock lock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "WifiLockTag");
lock.acquire();
and in onStartCommand I set the service to foreground, start the server and return START_STICKY
:
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle("Test")
.setContentText("Testing...")
.setOngoing(true)
.setContentIntent(pendingIntent).build();
startForeground(mNotificationId, notification);
webServer = new WebServer(this);
webServer.start();
WebServer extends NanoHTTPD and there I implemented serve( IHTTPSession session )
.
The ServerService is in the AndroidManifest:
<service
android:name=".ServerService"
android:enabled="true" />
What could be the problem?