【问题标题】:unable to start IntentService无法启动 IntentService
【发布时间】:2013-04-27 13:28:22
【问题描述】:

我在启动服务时获得了 NPE。我刚刚浏览了android开发者网站上的服务教程。

日志显示无法恢复活动...

@Override
protected void onResume() {
    super.onResume();
    CustomIntentService cis = new CustomIntentService();
    Intent intent1 = new Intent(this, CustomIntentService.class);
    intent1.putExtra("NUM", 1);
    cis.startService(intent1);
}

我的服务是:

public class CustomIntentService extends IntentService {
    private final static String TAG = "CustomIntentService";

    public CustomIntentService() {
        super("CustomIntentService");
        Log.d(TAG,"out CustomIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent");
        Log.d(TAG, "service num = " + intent.getIntExtra("NUM", 0));
        if (Looper.getMainLooper() == Looper.myLooper()) {
            Log.d(TAG, "In main ui thread");
        } else {
            Log.d(TAG, "In worker thread");
        }
    }   
}

【问题讨论】:

    标签: android service crash


    【解决方案1】:

    将 onResume 的代码更改为以下内容:

    @Override
    protected void onResume() {
        super.onResume();
        //CustomIntentService cis = new CustomIntentService();
        Intent intent1 = new Intent(this, CustomIntentService.class);
        intent1.putExtra("NUM", 1);
        startService(intent1);
    }
    

    这应该可以解决问题,记住 Intent 知道要启动哪个服务,并且 startService() 在上下文中被调用。所以这里活动的实例将是上下文。

    还有,

    由于 Service 是一个组件,所以你应该在 AndroidManifestFile 中声明它

    <service 
        android:name=".CustomIntentService">
    </service>
    

    *注意:CustomIntentService 应该在当前目录下,或者你也可以提供绝对路径。

    您可以参考this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多