我正在从我的主要活动开始一项服务。在服务完成之前,该活动不会出现。为什么会这样?这个问题的解决方案是什么?
问问题
550 次
3 回答
1
请详细阅读本文档。http://developer.android.com/guide/components/processes-and-threads.html
服务在 UI 线程上运行。您需要在不同的线程(可能是异步任务)中启动耗时的部分服务。
于 2013-02-20T07:11:39.950 回答
0
一个简单的示例服务,让您清楚如何使用它。
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class ServiceTimeToast extends Activity {
/** Called when the activity is first created. */
public static MyHandler myHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(ServiceTimeToast.this,ServiceManagement.class);
startService(intent);
myHandler = new MyHandler();
}
class MyHandler extends Handler
{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 111) {
//int count = Integer.parseInt(msg.obj);
int count = (Integer) msg.obj;
Log.i("MyLog", "Service Running Started"+count);
Toast.makeText(ServiceTimeToast.this, "Service Running properly::"+count, Toast.LENGTH_SHORT).show();
}
}
}
}
ServiceManagement.java // 服务类
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ServiceManagement extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v("MyLog", "OnCreate of the Service management called");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v("MyLog", "OnDestroy of the Service management called");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.v("MyLog", "onStartCommand of the Service management called");
ThreadTime t = new ThreadTime();
Thread thread = new Thread(t);
thread.start();
return super.onStartCommand(intent, flags, startId);
}
}
class ThreadTime implements Runnable
{
int MAX_SEC = 5;
//MyHandler handler = new MyHandler();
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("MyLog", "Thread Started!!");
int count = 0;
for(int i = 0;i<MAX_SEC;i++)
{
try {
Log.i("MyLog", "Inside the For loop!!!!!!");
Message message = ServiceTimeToast.myHandler.obtainMessage(111);
message.obj = ++count;
ServiceTimeToast.myHandler.sendMessage(message);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
}
于 2013-02-20T07:19:04.170 回答