加载中…
正文 字体大小:

A service runs in the main thread of its hosting&nb

(2013-05-31 14:56:41)
分类: android
Service
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
如过在主线程调用service,并进行网络链接此类的长时间操作,由于service还在主线程中,会造成主线程阻塞,所以4.0以后的系统无法访问网络。


在service中如果想要做耗时的操作,就要新建线程,或者使用IntentService类(源码分析),否则会造成主线程阻塞,无响应。
继承IntentService后,注意:
public int onStartCommand (Intent intent, int flags, int startId)
Added in API level 5
You should not override this method for your IntentService. Instead, override onHandleIntent(Intent), which the system calls when the IntentService receives a start request.
eg1
继承service
public void onStart(Intent intent, int startId) {  
    super.onStart(intent, startId);  
    //经测试,Service里面是不能进行耗时的操作的,必须要手动开启一个工作线程来处理耗时操作  
    System.out.println("onStart");  
    try {  
        Thread.sleep(20000);  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    }  
    System.out.println("睡眠结束");  
}  

继承intentService
public class MyIntentService extends IntentService {  
 
    public MyIntentService() {  
        super("yyyyyyyyyyy");                      //构造函数如果没有super("yyyyyyyyyyy");就会出现如下错误
//intentservice java.lang.InstantiationException: can't instantiate class... no empty constructor
    }  
  
    @Override  
    protected void onHandleIntent(Intent intent) {  
        // 经测试,IntentService里面是可以进行耗时的操作的  
        //IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent  
        //对于异步的startService请求,IntentService会处理完成一个之后再处理第二个  
        System.out.println("onStart");  
        try {  
            Thread.sleep(20000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("睡眠结束");  
    }  

 

0

阅读 评论 收藏 转载 喜欢 打印举报
  • 评论加载中,请稍候...
发评论

       

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 不良信息反馈 电话:4006900000 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有