如何为android开发人员创建后台服务

如何为android开发人员创建后台服务,android,Android,嗨,我是android新手,这也是我第一次在后台使用这个服务。 我的意思是,我想构建一个语音命令应用程序,我想让它即使在关闭时也能听到用户的命令。我想在任何用户按下“后退”按钮时启动我的服务。 我将非常感谢您的大力帮助。试试这个: import android.app.Service; 导入android.content.Intent; 导入android.os.IBinder 公共类Startappservice扩展服务{ @Override public IBinder onBind(In

嗨,我是android新手,这也是我第一次在后台使用这个服务。 我的意思是,我想构建一个语音命令应用程序,我想让它即使在关闭时也能听到用户的命令。我想在任何用户按下“后退”按钮时启动我的服务。 我将非常感谢您的大力帮助。

试试这个:

import android.app.Service;
导入android.content.Intent; 导入android.os.IBinder

公共类Startappservice扩展服务{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.enwaye_connect.MainActivity");
    startActivity( LaunchIntent );
}
要在单击“上一步”按钮时启动服务,请执行以下操作:

Intent start= new Intent(this, Startappservice .class);
        startService(start);
在您的清单中添加:

 <service android:name="your_package_name.Startappservice" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="our_package_name.Startappservice" />
        </intent-filter>
    </service>

您必须使用
服务
类。创建一个从它派生的类,然后您可以将您的方法添加到服务中

public class MyService extends Service {

    // This is used to establish a communication with the service.
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }


    // Called when the service is created
    @Override
    public void onCreate() {
       // YOUR CODE
    }

    // Called when the service is started
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // YOUR CODE
        return START_STICKY;
    }

    // called when the service instance is destroyed
    @Override
    public void onDestroy() {
         // YOUR CODE
    }

    // Returns the binder which is used for communication with the service.
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}
要启动服务,请使用:

Intent start= new Intent(this, MyService.class);
startService(start);

当然,我很快会查出来的