aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/com/arslaancodes/mokuassistant/AssistantService.java
blob: 7d381be3990e03246620683be3dfb89a52fe1606 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.arslaancodes.mokuassistant;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

public class AssistantService extends Service {
	private static final String TAG = "moku";
	private static final String CHANNEL_ID = "moku_assistant_channel";
	private static final String CHANNEL_NAME = "moku Assistant";
	private static final int NOTIFICATION_ID = 1001;

	@Override
	public void onCreate() {
		super.onCreate();
		createNotificationChannel();
		Log.i(TAG, "AssistantService created");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "AssistantService started");

		Notification notification = buildNotification();
		startForeground(NOTIFICATION_ID, notification);

		startAssistant();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "AssistantService destroyed");
		stopAssistant();
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void createNotificationChannel() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel(
				CHANNEL_ID,
				CHANNEL_NAME,
				NotificationManager.IMPORTANCE_LOW
			);
			channel.setDescription("Shows when moku Assistant is running");
			channel.setShowBadge(false);

			NotificationManager manager = getSystemService(NotificationManager.class);
			if (manager != null) {
				manager.createNotificationChannel(channel);
			}
		}
	}

	private Notification buildNotification() {
		Intent notificationIntent = new Intent(this, AssistantService.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(
			this,
			0,
			notificationIntent,
			PendingIntent.FLAG_IMMUTABLE
		);

		return new NotificationCompat.Builder(this, CHANNEL_ID)
			.setContentTitle("moku Assistant")
			.setContentText("listening...")
			.setSmallIcon(android.R.drawable.ic_btn_speak_now)
			.setContentIntent(pendingIntent)
			.setPriority(NotificationCompat.PRIORITY_LOW)
			.setOngoing(true)
			.build();
	}

	private static native void startAssistant();
	private static native void stopAssistant();

	static {
		System.loadLibrary("moku");
	}
}