I have a strange problem. I have an Activity with a ListView and start a service in the Activity in onCreate.
When I start the App now the Layout of the Activity is not shown until the service has done his work. =( Normaly the service should do his work in the background.
Activity
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);
}
...
}
Service
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;
}
}
Thank you for your help!
Services are automatically in the background from a UI standpoint. They are not automatically in the background from a threading standpoint.
onStartCommand()is called on the main application thread, and your UI will be frozen for however longonStartCommand()takes to complete. Hence, any significant work to be done by the service needs to be done in a background thread, whether it is one you create yourself or one you get by switching toIntentService.