9

我是 android 新手,我不太了解服务。我有一个带有 UI 的活动类,当我单击后退按钮时,我想让这个活动类在后台运行。如何让我的活动像服务一样在后台运行,请帮助我..

4

4 回答 4

5

你不能真正Activity在后台运行!当一个活动不在前台时,它会到达onStop然后系统可以终止它,通过onDestroy方法释放资源!请参阅活动生命周期

为了在后台运行,您需要创建一个ServiceIntentService

在此处此处查看有关服务的 android javadoc或IntentService

这是一个第三方Android服务教程

编辑:您可能还需要在您的服务和您的活动之间进行通信,以便您可以通过它:示例:使用消息传递的活动和服务之间的通信

于 2013-03-25T17:21:21.723 回答
4

如果您只是希望您的活动在后面运行,请尝试使用

moveTaskToBack(true);
于 2013-03-25T18:43:46.600 回答
0

似乎您想在退出时在后台运行活动。但是,除非在前台,否则无法运行活动。

为了实现你想要的,在 onPause() 中,你应该启动一个服务来继续活动中的工作。单击后退按钮时将调用 onPause()。在 onPause 中,只需保存当前状态,并将作业转移到服务。当您的活动不在前台时,该服务将在后台运行。

当您稍后返回您的活动时,请在 onResume() 中执行一些操作以再次将服务的工作转移到您的活动中。

于 2013-03-25T17:27:16.107 回答
-2

您应该阅读有关线程的开发人员指南:http: //developer.android.com/guide/components/processes-and-threads.html

特别是页面中的函数 doInBackground() 示例:

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
    return loadImageFromNetwork(urls[0]);
}

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}
于 2013-03-25T17:14:02.477 回答