我有一个按钮,按下后,启动服务。此服务开始从设备记录信息。然而,当我按下跑步时,屏幕在记录时暂时冻结约8秒,然后一旦完成屏幕解冻,就会显示一个祝酒消息(这意味着只要按下按钮就会显示)然后我可以做任何事情。如果我再次进入应用程序屏幕,当应用程序正在记录时(注意:服务始终在运行以便不冻结它,只记录日志)然后活动再次冻结,并且在记录完成之前不让我做任何事情。
我尝试过asynctasks并在一个新的runnable / new线程上运行,但这些似乎都不适用于我。无论我是否正确实施它我都不确定,但我想解决这个问题。
这是我在服务类中的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;
}
答案 0 :(得分:1)
服务在导致'冻结'的UI线程上运行。使用IntentService将创建一个自动在后台运行的服务,而不是在UI线程上运行。以下是IntentService类的一些细节:
答案 1 :(得分:0)
默认情况下,服务也会在您的应用程序的主线程中运行,您的UI操作将在该主线程中运行。因此,如果在onStartCommand()方法中执行长任务,它将阻止主线程。
要避免此问题,您必须将日志记录任务迁移到单独的线程中。您可以使用AsycTask类来执行此操作。有关如何使用该课程,请参阅http://developer.android.com/reference/android/os/AsyncTask.html。