java 如何使用构造函数实例化android服务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9999038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:12:25  来源:igfitidea点击:

How to instantiate android service with a constructor?

javaandroidserviceconstructor

提问by Milan

I have a service with an following constructor:

我有一个具有以下构造函数的服务:

public ShimmerService(Context context, Handler handler) {
    mHandler = handler;
}

I want to instantiate this service class. I have following code but, I am not sure where to pass the paramater:

我想实例化这个服务类。我有以下代码,但我不确定在哪里传递参数:

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        mShimmerService = ((ShimmerService.ShimmerConfigureBinder) binder)
                .getService();
        Toast.makeText(ConfigureShimmer.this,
                "Shimmer service has succesfully started.",
                Toast.LENGTH_SHORT).show();
    }

    public void onServiceDisconnected(ComponentName className) {
        mShimmerService = null;
    }
};

I have everything else setup including binding, on start and so on. But I get error in above code:

我有其他所有设置,包括绑定、启动等。但是我在上面的代码中遇到错误:

04-03 19:06:10.285: E/AndroidRuntime(16837): java.lang.RuntimeException: Unable to instantiate service com.milanix.androidecg.services.ShimmerService: java.lang.InstantiationException: can't instantiate class com.milanix.androidecg.services.ShimmerService; no empty constructor

How do I fix this problem? Where will i need to pass parameter? Following code works but, it rather uses service class as a class, rather than service:

我该如何解决这个问题?我需要在哪里传递参数?以下代码有效,但它宁愿使用服务类作为类,而不是服务:

mShimmerService = new ShimmerService(this, mHandler);

回答by Seva Alekseyev

You should not construct services (or activities, or broadcast receivers) explicitly. The Android system does that internally. The proper way to construct a service is via startService()with an intent; feel free to add extra parameters to that intent.

您不应显式构建服务(或活动或广播接收器)。Android 系统在内部执行此操作。构建服务的正确方法是通过startService()意图;随意为该意图添加额外的参数。

EDIT: or bindService(). Then you have options - either build a custom interface with AIDL, or use raw transact().

编辑:或bindService()。然后你有选择 - 要么用 AIDL 构建自定义界面,要么使用 raw transact()

回答by mohammad

intent service = new Intent(current context, your service name.class);
`service.putExtra(key,value);`// put your sightly variable type
`service.setAction("StartDownload");`// action that will detect in onStartCommand

 current context.startService(service);

in service, in onStartCommand:

在服务中,在 onStartCommand 中:

if (intent.getAction().equals("StartDownload")) {
`intent.getExtras().getString(key)`;// string in this sample should be your variable type as you used in your code
//do what you want
    }`

回答by Robert Estivill

Service extends Context, so you don't really need it as a parameter in your constructor, since you can use that same instance.

服务扩展了上下文,因此您实际上并不需要它作为构造函数中的参数,因为您可以使用相同的实例。

If you have any other parameters that you would like to pass in to the service, i would recommend adding them to the startService intent as extras and getting them in the service.onStartCommand method.

如果您有任何其他想要传递给服务的参数,我建议将它们作为附加项添加到 startService 意图中,并在 service.onStartCommand 方法中获取它们。

回答by VinoRosso

Dont pass the Handler to the Service, Handler doesnt implement Parcelable, or Serializable, so I dont think thats possible.

不要将处理程序传递给服务,处理程序没有实现 Parcelable 或 Serializable,所以我认为这不可能。

Create the Handler in the Service, and pass any data you need to create the Handler via Intent Extras to the Service.

在服务中创建处理程序,并将创建处理程序所需的任何数据通过 Intent Extras 传递给服务。

回答by koljaTM

You need to have a no-argument constructor for your Service class, otherwise the systems doesn't know how to instantiate it.

您的 Service 类需要有一个无参数的构造函数,否则系统不知道如何实例化它。

回答by rbrisuda

Instead of passing Handler (or whatever object) to the service (what is not possible by the way), you create and register BroadcastReceiver in your Activity class. When you need to invoke Handler functions (or whatever functions in another object) then send broadcast on registered receiver (sendBroadcast). You can also put additional extra parameters to the intent and you can handle all needed code directly from Activity according parameters.

不是将 Handler(或任何对象)传递给服务(顺便说一下,这是不可能的),而是在 Activity 类中创建和注册 BroadcastReceiver。当您需要调用处理程序函数(或另一个对象中的任何函数)时,然后在注册的接收器上发送广播 (sendBroadcast)。您还可以为意图添加额外的额外参数,并且您可以根据参数直接从 Activity 处理所有需要的代码。

Maybe, in this case your handler will be completely removed (Depends what you actually need.). With broadcast receivers, I don't know to imagine situation when you would need to pass some object to the Service. On the other hand, you doing something not good and you should review the design of the application.

也许,在这种情况下,您的处理程序将被完全删除(取决于您实际需要的内容。)。对于广播接收器,我无法想象您需要将某个对象传递给 Service 的情况。另一方面,你做了一些不好的事情,你应该应用程序的设计。

If we want something pass to the Service, we can only start Service with extra parameters in Intent. Service handles state according this parameters inside.

如果我们想要将某些东西传递给 Service,我们只能在 Intent 中使用额外的参数启动 Service。服务根据里面的这个参数处理状态。

The idea is that Service may run independently from other parts of applications e.g Activities. We may control it with extra parameters when we start Service or with sending broadcasts for invoking outside code.

这个想法是服务可以独立于应用程序的其他部分运行,例如活动。当我们启动 Service 或发送广播以调用外部代码时,我们可以使用额外的参数来控制它。