85 lines
2.9 KiB
Java
85 lines
2.9 KiB
Java
package com.codigoparallevar.minicards.bridge;
|
|
|
|
import android.app.Service;
|
|
import android.content.Intent;
|
|
import android.os.IBinder;
|
|
import android.os.Process;
|
|
import android.util.Log;
|
|
import android.widget.Toast;
|
|
|
|
import com.codigoparallevar.minicards.ConfigManager;
|
|
import com.programaker.api.ProgramakerApi;
|
|
|
|
public class ProgramakerBridgeService extends Service {
|
|
private ProgramakerAndroidBridge bridge = null;
|
|
private static final String LogTag = "PM BridgeService";
|
|
|
|
@Override
|
|
public void onCreate() {
|
|
}
|
|
|
|
@Override
|
|
public int onStartCommand(Intent intent, int flags, int startId) {
|
|
|
|
ConfigManager config = new ConfigManager(this);
|
|
|
|
String token = config.getToken();
|
|
String bridgeId = config.getBridgeId();
|
|
if (token == null || bridgeId == null) {
|
|
Toast.makeText(this, "Cannot start bridge", Toast.LENGTH_SHORT).show();
|
|
if (token == null) {
|
|
Log.e(LogTag, "Cannot start bridge: Token is null");
|
|
}
|
|
if (bridgeId == null) {
|
|
Log.e(LogTag, "Cannot start bridge: BridgeId is null (not created?)");
|
|
}
|
|
}
|
|
|
|
if (ProgramakerBridgeService.this.bridge != null) {
|
|
// Toast.makeText(this, "Bridge already started", Toast.LENGTH_SHORT).show();
|
|
Log.w(LogTag, "Bridge already started (not null)");
|
|
}
|
|
|
|
// Start up the thread running the service. Note that we create a
|
|
// separate thread because the service normally runs in the process's
|
|
// main thread, which we don't want to block. We also make it
|
|
// background priority so CPU-intensive work doesn't disrupt our UI.
|
|
Thread thread = new Thread(() -> {
|
|
try {
|
|
ProgramakerApi api = new ProgramakerApi();
|
|
api.setToken(token);
|
|
String userId = api.getUserId();
|
|
|
|
ProgramakerBridgeService.this.bridge = ProgramakerAndroidBridge.configure(
|
|
this,
|
|
userId,
|
|
bridgeId);
|
|
ProgramakerBridgeService.this.bridge.start(() -> {
|
|
ProgramakerBridgeService.this.bridge = null;
|
|
});
|
|
}
|
|
catch (Throwable ex) {
|
|
Log.e(LogTag, "Error on bridge", ex);
|
|
ProgramakerBridgeService.this.bridge = null;
|
|
}
|
|
}, "ServiceStartArguments");
|
|
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
|
thread.start();
|
|
Toast.makeText(this, "Starting bridge", Toast.LENGTH_SHORT).show();
|
|
|
|
// If we get killed, after returning from here, restart
|
|
return START_STICKY;
|
|
}
|
|
|
|
@Override
|
|
public IBinder onBind(Intent intent) {
|
|
// We don't provide binding, so return null
|
|
return null;
|
|
}
|
|
|
|
@Override
|
|
public void onDestroy() {
|
|
Toast.makeText(this, "Bridge stopped", Toast.LENGTH_SHORT).show();
|
|
}
|
|
}
|