简体   繁体   English

如何从android中的非Activity类调用服务方法

[英]how to call a service method from a non-Activity class in android

I saw this sample on how to bind a service and call its methods from an Activity. 我看到了关于如何绑定服务并从Activity调用其方法的示例。

http://developer.android.com/reference/android/app/Service.html#LocalServiceSample http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

But I want to bind a service and call its methods from a non-Activity class. 但我想绑定一个服务并从非Activity类调用它的方法。

how can I do this? 我怎样才能做到这一点?

as i don't have implementation of the following methods: 因为我没有实现以下方法:

bindService, unbindService

By the same way like from Activity just take/pass instance of content Activity 通过相同的方式从Activity获取/传递content Activity的实例

Lets say you have MyActivity class and OtherClass class 假设您有MyActivity类和OtherClass

so you run in OtherClass 所以你在OtherClass运行

 public class OtherClass {

    Context mContext;

    public void init(Context context){
      mContext = context;
    }
    ...

mContext.startService(new Intent(mContext, SomeService.class)); 

[EDIT] [编辑]

In your case: 在你的情况下:

Intent intent = new Intent(mContext, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

See documentation here 请参阅此处的文档

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

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