首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为android开发创建后台服务

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

Stack Overflow用户
提问于 2015-05-25 22:12:43
回答 2查看 26关注 0票数 0

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

EN

回答 2

Stack Overflow用户

发布于 2015-05-25 22:18:56

试试这个:

代码语言:javascript
复制
import android.app.Service;

导入android.content.Intent;导入android.os.IBinder;

公共类Startappservice扩展了服务{

代码语言:javascript
复制
@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 );
}

要在单击后退按钮时启动服务:

代码语言:javascript
复制
Intent start= new Intent(this, Startappservice .class);
        startService(start);

在您的清单中添加:

代码语言:javascript
复制
 <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>
票数 0
EN

Stack Overflow用户

发布于 2015-05-25 22:19:46

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

代码语言:javascript
复制
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;
    }
}

要启动服务,请使用:

代码语言:javascript
复制
Intent start= new Intent(this, MyService.class);
startService(start);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30440331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档