Files
MagicCaptainService/Assets/Plugins/Android/Main.java
2025-07-22 16:15:38 +08:00

94 lines
3.2 KiB
Java

package com.pinappletech.android.main;
import android.app.Service;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.ServiceInfo;
import android.os.Handler;
import android.os.Looper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main extends Service {
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable logRunnable = new Runnable() {
@Override
public void run() {
Log.i("PineappleService", "服务正在运行...");
// 5秒后再次执行
handler.postDelayed(this, 5000);
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("PineappleService", "菠萝服务启动");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"pineapple_channel",
"菠萝服务",
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
Notification notification = new Notification.Builder(this, "pineapple_channel")
.setContentTitle("菠萝服务")
.setContentText("运行中...")
.setSmallIcon(android.R.drawable.ic_notification_overlay)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
} else {
startForeground(1, notification);
}
// 启动定时日志任务
handler.post(logRunnable);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("PineappleService", "菠萝服务停止");
}
public static void startMyForegroundService() {
Log.i("PineappleService", "开始启动服务...");
try {
// 获取 UnityPlayer 类
Class<?> unityPlayerClass = Class.forName("com.unity3d.player.UnityPlayer");
// 获取 currentActivity 字段
Field activityField = unityPlayerClass.getField("currentActivity");
// 获取 Activity 实例
Object activity = activityField.get(null);
// 获取 getApplicationContext 方法
Method getApplicationContextMethod = activity.getClass().getMethod("getApplicationContext");
// 调用 getApplicationContext()
Context context = (Context) getApplicationContextMethod.invoke(activity);
// 创建 Intent 并启动前台服务
Intent intent = new Intent(context, Main.class);
context.startForegroundService(intent);
} catch (Exception e) {
Log.e("PineappleService", "启动服务失败: " + e.getMessage());
}
}
}