gpt4 book ai didi

java - 创建服务以检测用户的任何操作

转载 作者:行者123 更新时间:2023-11-30 10:23:32 24 4
gpt4 key购买 nike

我正在尝试创建一个服务,我想在其中检测有关用户的某些信息,假设当用户将设备放在 table 上时,我检测到了该操作,但我将其放在 MainActivty 上 并且我希望它放在 Service 上。问题是,在我的 MainActivity() 上,我调用了 registerAction(),在我的 onResume() 上,在 onPause 中调用了() 我从我的 sensor 调用了 unregisterListener(),还有一个 HandlerThread,我在 上启动它code>onCreate() 如何将其更改为 Service?会有问题吗?我发现没有相同的方法...

我已经创建了我的服务并且我有:

public class MyService extends Service {
public MyService() {
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}



@Override
public void onCreate() {
super.onCreate();
Log.d("CREATE","ONCREATE");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("DESTROY","ONDESTROY");
}
}

还有我的 MainActivity,我已经放置了 implements SensorEventListener

我类(class)的框架是:

    public class MainActivity extends Activity implements SensorEventListener {

private HandlerThread mSensorThread;
private SensorManager mSensorManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorThread = new HandlerThread("sensor_thread");
mSensorThread.start();
}

private void registerSensorListener() {
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST, new Handler(mSensorThread.getLooper()));
}

@Override
public void onSensorChanged(SensorEvent event) {
//DO stuff
if (isLayed()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("LAY","LAYLAY");
}
});
mSensorManager.unregisterListener(this);
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

private boolean isLayed() {


return stuff;
}


@Override
protected void onResume() {
super.onResume();

registerSensorListener();
}

@Override
protected void onPause() {
super.onPause();

mSensorManager.unregisterListener(this);
}
}

编辑

我正在使用 szamani20 代码,但我遇到了 runOnUiThread 问题,因为我也无法从我的 Service 调用,我遇到了这个问题

java.lang.RuntimeException: Unable to start service com.example.developer.qwe.MyService@d8c613b with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference

最佳答案

首先,您需要决定是否希望用户知道您正在运行的服务。对 Background Execution Limits in android Oreo 进行评论:

To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.

因此,考虑到您的情况,在许多情况下似乎有很多工作要做,使用前台服务会是更好的方法。作为android document says about foreground services :

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the Ongoing heading. This means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

既然您提到您检测到了操作,我就不会输入您的那部分代码。所以你需要创建一个子类 Service像你一样使用 startService获取它的方法 onCreate叫。您需要注意的一件事是 onCreate调用一次服务方法startService第一次使用该服务,无论您调用多少次startService再次 onCreate方法不会被调用,只有 onStartCommand被叫到。我们将这一事实与您可以在 intent 中提供字符串操作一起使用正确注册和注销您的听众。

MainActivity.java :

String action = "start";  // Or to unregister listener "stop"!
final Intent intent = new Intent(this, MyService.class);
intent.setAction(action);
startService(intent);

然后在MyService.java :

@Override
public void onCreate() {
super.onCreate();
// Do initialization or whatever here (executed once per service lifecycle)
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("start")) {
// Register your listener or whatever
showForegroundNotification();
}
if (intent.getAction().equals("stop")) {
// Unregister your listener or whatever
stopForeground(true);
stopSelf();
}

return START_STICKY;
}

private void showForegroundNotification() {
Intent myServiceNotificationIntent = new Intent(this, MainActivity.class);
myServiceNotificationIntent.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, MY_SERVICE_REQUEST_CODE,
myServiceNotificationIntent, MY_SERVICE_FLAG);

Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(MY_SERVICE_NOTIFICATION_CONTENT_TITLE)
.setTicker(MY_SERVICE_NOTIFICATION_TICKER)
.setContentText(MY_SERVICE_NOTIFICATION_CONTENT_TEXT)
.setSmallIcon(R.drawable.ic_whatever)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(MY_SERVICE_NOTIFICATION_ID, notification);
}

最后不要忘记在 onDestroy 中注销您的监听器如果 android 终止了您的服务(这种情况非常罕见):

@Override
public void onDestroy() {
super.onDestroy();
// Unregister your listener
}

关于java - 创建服务以检测用户的任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com