Android 如何在意图服务中获取上下文

Android 如何在意图服务中获取上下文,android,intentservice,Android,Intentservice,下面是一个场景:我有一个WakefulBroadcastReceiver,它执行 备份到网络计算机或云。它将在晚上爆炸 半夜,当我知道平板电脑将可以访问 局域网。备份会将数据存储到一个位置和一个文件,该位置和文件是由实例化WakefulBroadcastReceiver的片段“拾取”的, 使用存储访问框架。所以我需要能够访问 ContentResolver,要做到这一点,我需要上下文 从我阅读的所有文件来看,这是 BroadcastReceiver旨在用于潜在的长时间运行 在没有太多其他任务的情

下面是一个场景:我有一个WakefulBroadcastReceiver,它执行 备份到网络计算机或云。它将在晚上爆炸 半夜,当我知道平板电脑将可以访问 局域网。备份会将数据存储到一个位置和一个文件,该位置和文件是由实例化WakefulBroadcastReceiver的片段“拾取”的, 使用存储访问框架。所以我需要能够访问 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参考 此处的手动代码:

所以我的问题是如何在IntentService中获取上下文


IntentService
上下文
,因为
IntentService
继承自
上下文

,只需调用
getApplicationContext()

使用BackupSchedulingService即可获得上下文

原因: 服务扩展ContextWrapper

ContextWrapper扩展了上下文

您可以在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);
    }
    }

您可以使用意图服务类作为上下文。因为这是类的层次结构

  • android.content.Context
    • android.content.ContextWrapper
      • android.app.Service
        • android.app.IntentService
所以在java中

BackupSchedulingService。此

而在科特林

this@BackupSchedulingService

希望这将有助于未来的开发人员……

getApplicationContext()和使用“this”之间有什么区别?它在“受保护的void onHandleContent(Intent){”中起作用,但在IntentService中不起作用constructor@Moises你能解释一下原因吗?