简体   繁体   English

从一个活动启动意向服务并将结果发送给另一个活动

[英]Start intent service from one activity and send result to another

I have an android app with an activity ( Activity A ) that shows an image for 3 seconds (splash screen) and after that the main activity ( Activity B ) will start. 我有一个带有活动的Android应用程序( 活动A ),显示3秒的图像(启动画面),之后主活动( 活动B )将开始。

In my main activity I start a service to fetch some data from web but this work take some time and the user become uncomfortable. 在我的主要活动中,我启动了一项服务,从网络上获取一些数据,但这项工作需要一些时间,用户会感到不舒服。

What I want is to start the service from Activity A and send the result to Activity B to show some results to user. 我想要的是从活动A启动服务并将结果发送到活动B以向用户显示一些结果。 The problem is that I don't have an instance of Activity B in the Activity A to send the ResultReceiver instance to IntentService . 问题是我在活动A中没有活动B的实例来将ResultReceiver实例发送到IntentService

How can I do this? 我怎样才能做到这一点?

I have a nested class in Activity B that extends ResultReceiver . 我在Activity B中有一个扩展ResultReceiver的嵌套类。

Sounds like you need a data model to hold the data between activities. 听起来你需要一个数据模型来保存活动之间的数据。

One solution would be to create a static class or use the singleton design pattern. 一种解决方案是创建静态类或使用单例设计模式。 This could take the result from the service. 这可以从服务中获得结果。 You would initialise this in Activity A and start the service before firing the intent for Activity B 您可以在活动A中初始化它并在激活活动B的意图之前启动服务

Then in activity B you can send a call a method to register it's call back function. 然后在活动B中,您可以发送一个调用方法来注册它的回调函数。 If the data is there come back straight away to the call back function. 如果数据在那里直接返回到回叫功能。 If not do so when your new class is called back from the function. 如果在从函数中调用新类时不这样做。

Your data is then shared and only fetched/refreshed as and when you need it to be. 然后,您的数据将被共享,并且只在您需要时才会获取/刷新。

// ----------- Class to hold your data Item ----------- // -----------用于保存数据项的类-----------

   public class DataItem {

        private Integer id = -1;

        // My Data stuff
        public Integer getId() {
            return this.id;
        }
    }

// ----------- Interface to join it all together ----------- // -----------将它们连接在一起的界面-----------

    import java.util.ArrayList;

    public interface NotifiyDataInterface {

        public void completedDataLoad( ArrayList data, String status);

    }

// ----------- Singleton Class for the datafetching ----------- // -----------用于数据提取的Singleton类-----------

    public class DataFetcher {

        static DataFetcher _instance = null;

        ArrayList<NotifiyDataInterface> _callBackList = null;
        ArrayList<DataItem> _cachedData = null;
        String _dataStatus = "";

        public DataFetcher() {
            _callBackList = new ArrayList<NotifiyDataInterface>();
        }

        public static DataFetcher getInstance() {

            if (DataFetcher._instance == null) {
              DataFetcher._instance = new DataFetcher();  
            }

            return _instance;
        }


        public void fetchData(NotifiyDataInterface _callBack) {

            if (_cachedData != null) {
                _callBack.completedDataLoad(this._cachedData, this._dataStatus);
                return;
            }

            // Add to the call back list
            this._callBackList.add(_callBack);

            // Code to call your service to get data
            //TODO: Add code to call your service

        }


        public void dataLoadComplete(ArrayList<DataItem> _newItems, String _fetchStatus) {
            // Called from the service on a completed data load

            this._cachedData = _newItems;
            this._dataStatus = _fetchStatus;

            NotifiyDataInterface _item = null;

            for (int i = 0; i < _callBackList.size(); i++) {
                _item = _callBackList.get(i);
                _item.completedDataLoad(this._cachedData, this._dataStatus);
            }

            // Clear out the call back list
            _callBackList.clear();
        }

    }

// ----------- Class for activity B ----------- // -----------活动B的类-----------

public class ActivityB  extends ActionBarActivity implements NotifiyDataInterface {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        // Get the single instance from the singleton pattern
        DataFetcher dataFetcher = DataFetcher.getInstance();
        dataFetcher.fetchData(this);
    }

    // Here is where you call back is fired
    public void completedDataLoad( ArrayList data, String status) {
        //TODO: Your Code to call on data load here
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.layout.activity_b, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM