1

我想我可以传递一个启动Started Service. 由于服务具有 Activity 的引用,它可以调用该引用的方法。

现在,如果 Activity 被销毁,但服务仍在后台运行,如果服务调用 Activity 引用的方法会发生什么?

4

1 回答 1

1

您绝对应该避免存储对一般活动的引用。如果是这样,你必须在活动中释放它onDestroy(),否则你会得到内存泄漏。您将引用存储在服务中的原因是什么?

EDIT:

您可以使用 toast 通知或状态栏通知来通知用户后台工作已完成。这是一种常见的做法。如果您需要与一个 通信Activity,有几种方法可以完成它。您可以绑定到一个Activity、使用Intents或使用AIDL。您可以在此处查看更多详细信息。

我描述了IntentsResultReceiver一起使用的选项之一。

Service在应用程序的主线程中运行,因此如果您正在执行阻塞操作,您应该在服务内启动一个新线程。在这种情况下,您可以使用IntentService为您简化工作并且已经实现了线程化的东西。

我将从ResultReceiverServiceResultReceiver进行自定义扩展。比我在我的和启动接收器对象时实现它的接口。ActivityServiceIntentService

自定义ResultReceiver

public class ServiceResultReceiver extends ResultReceiver {

    private Receiver mReceiver;

    public ServiceResultReceiver(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    public interface Receiver {
        public void onReceiveResult(int resultCode, Bundle resultData);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode, resultData);
        }
    }
}

你的Activity

public class MyActivity extends Activity implements ServiceResultReceiver.Receiver {
    private ServiceResultReceiver mReceiver;
    ...

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        mReceiver = new ServiceResultReceiver(new Handler());
        mReceiver.setReceiver(this);
        // starting a service
        final Intent intent = new Intent(this, MyService.class);
        intent.putExtra("receiver", mReceiver);
        startService(intent);
    }
    ...

    @Override
    public void onReceiveResult(int resultCode, Bundle resultData) {
        // here you can handle data which came from your service.
        Toast.makeText(this, "onReceiveResult()", Toast.LENGTH_SHORT).show();
    }

你的Service

public class MyService extends IntentService {
    ...
    @Override
    protected void onHandleIntent(Intent intent) {
        // executing your task
        ...
        // getting the receiver and sending back data in Bundle (here in this example we are sending no data)
        final ResultReceiver receiver = intent.getParcelableExtra("receiver");
        if (receiver != null) {
            receiver.send(0, null);
        }
    }
}
于 2012-07-20T19:50:38.080 回答