gpt4 book ai didi

java - 运行服务时 Activity 卡住

转载 作者:行者123 更新时间:2023-11-30 11:35:49 25 4
gpt4 key购买 nike

我有一个按钮,当按下它时,它会启动一项服务。该服务开始从设备记录信息。但是,当我按下运行时,屏幕在记录时会暂时卡住大约 8 秒,然后一旦完成屏幕就会解冻,显示一条提示消息(这意味着一旦你按下按钮就会显示)然后我可以为所欲为。如果我再次进入应用程序屏幕,当应用程序正在记录时(注意:服务始终在运行,因此不会卡住它,只是记录)然后 Activity 将再次卡住并且在记录完成之前不会让我做任何事情。

我尝试过异步任务并在新的可运行/新线程上运行,但这些似乎都不适合我。我不确定是否正确实现了它们,但我想解决这个问题。

这是我在服务类中的 onStartCommand:

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// THIS WOULD BE THE METHOD THAT RUNS WHATEVER YOU WANT TO DO EVERY SO OFTEN SO FOR ME THIS IS GETTING ALL DATA ETC
getProcessInfo();

// LOG DELAY = SECONDS BETWEEN RUNNING SERVICE/METHOD. SET AT THE TOP
myPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Alarmmgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+LOG_DELAY*1000, myPendingIntent);
Intent notificationIntent = new Intent(this, LogOrCheck.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
101, notificationIntent,
PendingIntent.FLAG_NO_CREATE);

NotificationManager nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = this.getResources();
Notification.Builder builder = new Notification.Builder(this);

builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.arrow_up_float)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_down_float))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("Androigenius")
.setContentText("Service running OK");
Notification n = builder.getNotification();


startForeground(100, n);
return Service.START_STICKY;
}

这里是我调用 startService 的地方:

but1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

if (isClicked) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Please press 'MINIMIZE' at the top to continue logging.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 10, 55);
toast.show();
System.out.println("Start logging");
but1.setText("Stop Logging");
but1.setTextColor(Color.RED);
// START SERVICE, DONE. (STOP IS BELOW).
startService(myIntent);
isClicked = false;
}
else if (!isClicked) {
System.out.println("Stop Logging");
but1.setText("Start Logging");
// STOP SERVICE, DONE.
stopService(myIntent);
but1.setTextColor(getResources().getColor(color.cornblue));
isClicked = true;
}

最佳答案

服务在导致“卡住”的 UI 线程上运行。使用 IntentService 将创建一个自动在后台运行的服务,而不是在 UI 线程上。以下是 IntentService 类的一些细节:

IntentService Class

关于java - 运行服务时 Activity 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877947/

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