Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从活动启动服务_Android_Android Service - Fatal编程技术网

Android 从活动启动服务

Android 从活动启动服务,android,android-service,Android,Android Service,在我的应用程序中,我有一个活动,我想从中启动服务。任何人都可以帮助我吗?有一些启动服务的示例。使用Context.startService()方法 和读取。应用程序可以在.startService方法的帮助下启动服务。如果尚未创建服务,则该方法将调用该服务的onCreate方法;否则将调用onStart方法。代码如下: Intent serviceIntent = new Intent(); serviceIntent.setAction("com.testApp.service.MY_SERV

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

有一些启动服务的示例。

使用Context.startService()方法


和读取。

应用程序可以在.startService方法的帮助下启动服务。如果尚未创建服务,则该方法将调用该服务的onCreate方法;否则将调用onStart方法。代码如下:

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

将此添加到代码中

Intent serviceIntent = new Intent(this, ServiceName.class);
    startService(serviceIntent);
别忘了在AndroidManifest.xml文件中添加服务标记

<service android:name="com.example.ServiceName"></service>

从:

注意:服务与中的应用程序在同一进程中运行 在该应用程序的主线程中 违约因此,如果您的服务执行密集或阻塞操作 当用户与来自同一应用程序的活动交互时, 该服务将降低活动性能。避免碰撞 应用程序性能,您应该在 服务


首先从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));
}

如果您想启动一个服务,并且它应该在后台运行,请在相应的服务中使用start\u STICKY

您也可以在开机时启动服务

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

您的服务就像,

kotlin
中,您可以从以下活动开始服务:

   startService!!.setOnClickListener { startService() }
 
   private fun startService(){
    startService(Intent(this, HitroService::class.java))
   }
@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;
        }
    }
}
   startService!!.setOnClickListener { startService() }
 
   private fun startService(){
    startService(Intent(this, HitroService::class.java))
   }