如何在Intent Service中获取上下文(Context)

47

这是场景:我有一个WakefulBroadcastReceiver,会在晚上备份到网络计算机或云端。它被设置在深夜触发,当我知道平板电脑可以访问局域网时。备份将把数据存储到一个位置和文件中,该位置和文件是由实例化WakefulBroadcastReceiver的片段通过Storage Access Framework进行选择的。因此,我需要能够访问ContentResolver,并为此我需要上下文。

根据我阅读的所有文档,这就是BroadcastReceiver的用途-一个可能运行时间长且在没有大量其他操作发生时应在后台完成的任务。-像备份一样。只是我还没有看到将所有内容组合在一起的示例。

如何在IntentService中获取上下文?这里是接收器和调度服务的代码片段。

  public class BackupAlarmReceiver extends WakefulBroadcastReceiver {

    @Override
        public void onReceive(Context context, Intent intent) {

            Intent service = new Intent(context, BackupSchedulingService.class);

        startWakefulService(context, service);

        }
}

public class BackupSchedulingService extends IntentService {
    public BackupSchedulingService() {
        super("BackupSchedulingService");
    }

 @Override
    protected void onHandleIntent(Intent intent) {

        Bundle extras = intent.getExtras(); 
        // How to get the context - it was a parameter when
        // creating the new IntentService class above? 
         }
}

这个示例代码基本上完全遵循了Android参考手册中的代码:

https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

5个回答

88
所以我的问题是如何在IntentService中获取上下文? IntentService就是Context,因为IntentService继承自Context。

39

只需调用 getApplicationContext()


'getApplicationContext()' 和使用 'this' 有什么区别? - Zapnologica
7
在“protected void onHandleIntent(Intent intent) {”中是可以工作的,但在IntentService构造函数中则不行。 - Moisés
@Moises,你能解释一下为什么吗? - SLearner

9
您可以在onStartCommand()函数中获取上下文。
    public class ExampleService extends IntentService {
    private Context mContext;

    public ExampleService(String name) {
    super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    mContext = getApplicationContext();
    return super.onStartCommand(intent, flags, startId);
    }
    }

2

使用BackupSchedulingService.this(ServiceName.this)获取Context。

原因: Service扩展了ContextWrapper
ContextWrapper扩展了Context


2

您可以将IntentService类用作Context,因为这是IntentService类的层次结构。

  • android.content.Context
    • android.content.ContextWrapper
      • android.app.Service
        • android.app.IntentService

所以在Java中:

BackupSchedulingService.this

而在Kotlin中:

this@BackupSchedulingService

希望这能帮助未来的开发人员...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接