【问题标题】:How I can know if the context is Activity or IntentService?我如何知道上下文是 Activity 还是 IntentService?
【发布时间】:2015-07-27 17:50:29
【问题描述】:

我在一个变量中有上下文,我怎么知道上下文是不是intentService?

public void syncToServer(Context context){
    if ( is intentService ){
        hpptClientSend();
    }else{
        hpptClientAsyncSend();
    }
}

问题是当我想在使用 httpclient 的 intentservice AsyncTask 中使用时,因为 android 不允许在服务中使用并行线程: An asyncTask launched from an onPostExecute of another AsyncTask does not execute properly in API 10

我需要在 IntentService 中使用 httpClient,但我在 UI 线程中使用了相同的功能并且需要 AsynkTask。

【问题讨论】:

  • 如何将 Intent 对象作为参数传递给syncToServer
  • "我如何知道上下文是 Intent 还是 intentService?" -- Intent 不扩展 Context
  • njzk2 谢谢 :) 工作正常。 CommonsWare 你是对的,它是活动或意图服务。 ρяσѕρєя 非常难,有很多函数依赖于它,尽管有可能,但你必须修改所有类型的函数才能实现这一点。

标签: java android multithreading android-intent android-asynctask


【解决方案1】:

在 Java 中,使用 instanceof 运算符来确定对象是否是某个类或接口的实例。因此,如果contextIntentService(或IntentService 的某个子类)的一个实例,context instanceof IntentService 将是true,否则false

【讨论】:

  • 是否有另一种方法可以直接从上下文对象中获取实例类型?所以与其问,“这个上下文实例是类型 A、B、C 吗……?”你问,“你是什么实例类型?”
  • @CodeNovice:您可以在 Java 对象上调用 getClass() 以返回其 Class,如果您的意思是这样的话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 2016-11-17
  • 2023-03-30
相关资源
最近更新 更多