-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathService.java
More file actions
80 lines (66 loc) · 2.6 KB
/
Copy pathService.java
File metadata and controls
80 lines (66 loc) · 2.6 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
package com.kamwithk.ankiconnectandroid;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.MutableLiveData;
import com.kamwithk.ankiconnectandroid.routing.Router;
import java.io.IOException;
import static com.kamwithk.ankiconnectandroid.MainActivity.CHANNEL_ID;
public class Service extends android.app.Service {
public static final int PORT = 8765;
private Router server;
// LiveData to observe service state
public static final MutableLiveData<Boolean> serviceRunningState = new MutableLiveData<>(false);
@Override
public void onCreate() { // Only one time
super.onCreate();
try {
server = new Router(PORT, this);
} catch (IOException e) {
Log.e("Httpd", "The Server was unable to start.", e);
stopSelf(); // Stop the service if the server can't start
return;
}
}
@SuppressLint("UnspecifiedImmutableFlag")
@Override
public int onStartCommand(Intent intent, int flags, int startId) { // Every time start is called
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
} else {
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ankiconnect Android")
.setContentText("AnkiConnect service is running.")
.setSmallIcon(R.mipmap.app_launcher)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(1, notification);
// Update LiveData on main thread
serviceRunningState.postValue(true);
return START_STICKY;
}
@Override
public void onDestroy() {
if (server != null) {
server.stop();
}
// Update LiveData on main thread
serviceRunningState.postValue(false);
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}