我有一个奇怪的问题。我有一个带有 ListView 的 Activity,并在 onCreate 的 Activity 中启动了一个服务。
当我现在启动应用程序时,在服务完成其工作之前不会显示 Activity 的布局。 =(通常服务应该在后台完成他的工作。
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);
}
...
}
服务
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;
}
}
感谢您的帮助!
最佳答案
从 UI 的角度来看,服务自动处于后台。从线程的角度来看,它们不会自动在后台运行。 onStartCommand()
在主应用程序线程上调用,无论 onStartCommand()
需要多长时间才能完成,您的 UI 都会被卡住。因此,服务要完成的任何重要工作都需要在后台线程中完成,无论是您自己创建的线程还是通过切换到 IntentService
获得的线程。
关于android - Activity 正在等待直到服务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969076/