Android RuntimeException:无法实例化服务 [英] Android RuntimeException: Unable to instantiate the service

查看:25
本文介绍了Android RuntimeException:无法实例化服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个将在单独的线程(而不是 UI 线程)上运行的服务,因此我实现了一个将扩展 IntentService 的类.但我没有任何运气.这是代码.

I want to create a service which will run on a separate thread (not on UI Thread), so I implemented a class which will extend IntentService. But I haven't got any luck. Here is the code.

public class MyService extends IntentService {

    public MyService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

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

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e("Service Example", "Service Started.. ");
        // pushBackground();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.e("Service Example", "Service Destroyed.. ");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        // TODO Auto-generated method stub
        for (long i = 0; i <= 1000000; i++) {
            Log.e("Service Example", " " + i);
            try {
                Thread.sleep(700);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

活动按钮中的服务消耗点击:

Service Consumption in an Activity Button click:

public void onclick(View view) {
Intent svc = new Intent(this, MyService.class);
    startService(svc);
}

推荐答案

在您的具体实现中,您必须声明一个默认构造函数,它调用抽象 IntentService 的 public IntentService (String name) 超构造函数你扩展的类:

In your concrete implementation you have to declare a default constructor which calls the public IntentService (String name) super constructor of the abstract IntentService class you extend:

public MyService () {
  super("MyServerOrWhatever");
}

如果超级实现适合您(我期望),您不需要覆盖 onStartCommand.

You do not need to overwrite onStartCommand if the super implementation fits for you (what I expect).

在您当前的情况下,您应该得到一个异常(无法实例化服务...) - 将其放在问题中总是值得的.

In your current case you should get an exception (Unable to instantiate service...) - it is always worth to put this in the question.

这篇关于Android RuntimeException:无法实例化服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆