2012-06-10 37 views
2

我有一個奇怪的問題。我有一個ListView活動,並在onCreate中的Activity中啓動一個服務。活動正在等待,直到服務完成

當我啓動應用程序時,直到服務完成他的工作後才顯示活動的佈局。 =(Normaly服務應該做他的工作背景。

活動

import java.util.ArrayList; 
import java.util.HashMap; 
import android.app.Activity; 
import android.app.ActivityManager; 
import android.app.ActivityManager.RunningServiceInfo; 
import android.content.Intent; 
import android.os.Bundle; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 

public class DealAlertMainActivity extends Activity { 

    ListView list; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     list = (ListView) findViewById(R.id.list); 

     //start service if its not running 
     if(isMyServiceRunning() == false) 
      startService(new Intent(DealAlertMainActivity.this, DealAlert_Service.class)); 
    } 

    @Override 
    public void onStart() 
    { 
     super.onStart(); 

     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map = new HashMap<String, String>(); 
     map.put("keyword", "Test Keyword"); 
     map.put("title", "Test Title"); 
     mylist.add(map); 
     map = new HashMap<String, String>(); 
     map.put("keyword", "Test Keyword 2"); 
     map.put("title", "Test Title 2"); 
     mylist.add(map); 

     SimpleAdapter feeds_list = new SimpleAdapter(this, mylist, R.layout.listview_item, 
        new String[] {"keyword", "title"}, new int[] {R.id.Keyword, R.id.Title}); 
     list.setAdapter(feeds_list); 

    } 

... 

} 

服務

import java.util.ArrayList; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 


public class DealAlert_Service extends Service { 

    private NotificationManager mNM; 

    public void onCreate() 
    { 
     super.onCreate(); 

     mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    } 





    public int onStartCommand(Intent intent, int flags, int startId) { 

     //Do work 

     } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 

    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

} 

謝謝您的幫助!

回答

0

服務在後臺自動爲從UI的角度來看,它們是而不是在線程背景下自動處於在主應用程序線程上調用,並且您的UI將被凍結,但要花費很長的時間完成onStartCommand()。因此,服務需要完成的任何重要工作都需要在後臺線程中完成,不管它是您自己創建的還是通過切換到IntentService而獲得的。

+0

你確定嗎?因爲我有另一個應用程序,我使用相同的代碼,它運作良好。 :O那麼我應該在哪裏使用後臺線程?在Acitvity或服務中,你覺得它更好? – Stefan

+0

@Stefan:「你確定嗎?」 - 是的。 「因爲我有另一個應用程序,我使用相同的代碼,它運作良好。」 - 你在'onStartCommand()'中做的工作要麼很快,要麼使用後臺線程。 「在Acitvity或服務中,你覺得它更好?」 - 我無法回答,抱歉。 – CommonsWare

+0

好的,但是,謝謝,我現在與IntentService一起工作! – Stefan