我有一個按鈕,當按下時,啓動服務。該服務開始從設備記錄信息。然而,當我按下跑步時,屏幕會在記錄時暫時凍結約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;
}
我有同樣的問題.. 嗯,我明白意圖服務於一個單獨的線程運行,但我的UI依然凝固起來。我在意圖服務上做了一個很長的數據庫操作,我不明白爲什麼它會在完全不同的線程上運行。 – Guru 2013-09-12 14:14:57