繁体   English   中英

如何在Intent构造函数的第二个参数上传递上下文

[英]How to pass a context on the second parameter on Intent contructor

我有一个服务,其构造函数会接收上下文。 我想使用context.startService(Intent)方法初始化该Service,并传递一个Intent作为参数。 初始化意图

intent = new Intent(context, GpsService.class)

但是我需要将Context传递给第二个参数,因为在此类中,我需要Context来初始化LocationManager。

或者,您可以在没有上下文的情况下初始化LocationManager,因为我需要使用LocationManager查找位置

谢谢

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.app.Service

您为什么要将上下文传递给服务? 该服务也是上下文!

只需使用this关键字,因为服务将被强制转换为Context!

我需要使用Context来初始化LocationManager。

Service内部,可以使用getApplicationContext() ,该引用将为您提供对全局上下文对象的引用。 因此,您无需传递Activity的上下文。

您可以在服务中使用this关键字,因为服务已经包含上下文。 像这样

@Override
    public void onStart(Intent intent,  int startId) {
        super.onCreate();
        // you can use this here as mentioned in the toast
         Toast.makeText(this,"Monitoring Started", Toast.LENGTH_LONG).show();

         //ServiceHandler is the class name of this service
            SQLiteHelper sqh = new SQLiteHelper(ServiceHandler.this); 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM