从Activity启动一个服务

32

在我的应用程序中,我有一个Activity,我想从中启动一个服务。有人可以帮我吗?

7个回答

61

在你的代码中添加这个

Intent serviceIntent = new Intent(this, ServiceName.class);
    startService(serviceIntent);
不要忘记在AndroidManifest.xml文件中添加服务标签。
<service android:name="com.example.ServiceName"></service>

来自Android官方文档:

注意: 默认情况下,服务在声明它的应用程序的同一进程和主线程中运行。因此,如果您的服务在用户与同一应用程序的活动交互时执行密集或阻塞操作,服务将会减慢活动性能。为了避免影响应用程序性能,您应该在服务内部启动一个新线程。


43

应用程序可以通过使用Context.startService方法来启动服务。如果服务尚未创建,则该方法将调用服务的onCreate方法;否则将调用onStart方法。以下是代码:

Intent serviceIntent = new Intent();
serviceIntent.setAction("com.testApp.service.MY_SERVICE");
startService(serviceIntent);

2

首先,从 Android 的 Manifest.xml 文件中创建服务(即从应用程序选项卡中),并给它一个名称。
在活动中的某个事件(如点击或触摸)中,包含来自服务的代码:

public void onClick(View v)
{
    startService(new Intent(getApplicationContext(),Servicename.class));
}

如果您想停止正在运行或已启动的服务,请包含以下代码:

public void onclick(View v)
{
    stopService(new Intent(getApplicationContext,Servicename.class));
}

1

API演示 有一些启动服务的例子。


1
使用Context.startService()方法。
并阅读this

0
如果你想要启动一个在后台运行的服务,可以在你对应的服务中使用START_STICKY。
同时,你也可以在系统启动时自动启动服务。
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

并创建接收器,

<receiver android:name=".auth.NotificationBroadcast" android:enabled="true" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

在广播接收器中添加:
@Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("BroadcastReceiverBroadcast--------------------ReceiverBroadcastReceiverBroadcastReceiver----------------BroadcastReceiver");

        if (intent != null) {
            String action = intent.getAction();

        switch (action) {
            case Intent.ACTION_BOOT_COMPLETED:
                System.out.println("Called on REBOOT");
                // start a new service 
               startService(new Intent(getApplicationContext(),Servicename.class));

                break;
            default:
                break;
        }
    }
}

而你们的服务就像是:


0

kotlin 中,您可以按照以下方式从活动启动服务:

   startService!!.setOnClickListener { startService() }
 
   private fun startService(){
    startService(Intent(this, HitroService::class.java))
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接