在Android开发中,可以通过以下步骤给自己new的Service提供上下文:

  1. 在Service类的构造函数中添加一个参数来接收上下文:
public class MyService extends Service {
    private Context mContext;

    public MyService(Context context) {
        mContext = context;
    }
    
    // 其他代码...
}
  1. 创建Service实例时,传入一个上下文对象:
MyService myService = new MyService(getApplicationContext());

或者

MyService myService = new MyService(this);

请注意,上述代码中的上下文对象可以是应用程序的上下文(getApplicationContext())或当前活动的上下文(this)。具体使用哪种上下文对象取决于你的需求和使用场景。

使用这种方法,你就可以在Service中使用传入的上下文对象进行各种操作,如访问资源、启动Activity等

android开发: 自己new 的一个service怎么给它上下文

原文地址: https://www.cveoy.top/t/topic/inja 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录