【问题标题】:Send data from Service to Fragment, Android将数据从 Service 发送到 Fragment,Android
【发布时间】:2015-07-29 17:30:09
【问题描述】:

晚上好!
我的服务有小问题。起初,我有几个 TextViews 的片段。我想将我的服务中的文本放入这些 TextView 中。而我的简单服务的这段代码

public class ChallengeService extends Service {
    final String LOG_TAG = "myLogs";
    private String url = "";
    public static ArrayList<Exercises> exercises = new ArrayList<>();

    public void onCreate() {
        super.onCreate();
        Log.d(LOG_TAG, "onCreate");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "onStartCommand");
        url = intent.getStringExtra("Challenge_URL");
        new getChallenge(url).execute();
        return super.onStartCommand(intent, flags, startId);
    }

    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "onDestroy");
    }

    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "onBind");
        return null;
    }

    public class getChallenge extends AsyncTask<Void,Void,String> {

        String mUrl;
        OkHttpClient client = new OkHttpClient();
        String result = "";

        public getChallenge(String url) {
            this.mUrl = url;
        }

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        @Override
        protected String doInBackground(Void... params) {
            Log.d("Background", "inBackground");
            try {
                URL mUrl = new URL(url);
                Log.d("URL!!!!", "url = " + url);
                urlConnection = (HttpURLConnection) mUrl.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                result = buffer.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);
            Log.d(LOG_TAG, strJson + " " + url);
            exercises = ParseJSON.ChallengeParseJSON(strJson);
            Log.d("Challenges", "challenges: " + exercises.get(0).getName() + " " + exercises.get(1).getName());
        }
    }
}

我需要将 练习 列表发送到我的 Fragment,我该怎么做? 我是服务新手,我不知道,请帮助我

【问题讨论】:

    标签: android android-fragments service android-service


    【解决方案1】:

    只需广播来自您的服务的结果并通过广播接收器在您的片段中接收它

    例如,您可以像这样在onPostExecute 中广播您的练习

        @Override
        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);
            Log.d(LOG_TAG, strJson + " " + url);
            exercises = ParseJSON.ChallengeParseJSON(strJson);
            Log.d("Challenges", "challenges: " + exercises.get(0).getName() + " " + exercises.get(1).getName());
    
            Intent intent = new Intent(FILTER); //FILTER is a string to identify this intent
            intent.putExtra(MY_KEY, exercises); 
            sendBroadcast(intent);
        }
    

    但是,您的练习对象必须是 parcelable 才能顺利进行。或者你可以广播你的原始 json 字符串并在你的片段中调用你的ParseJSON.ChallengeParseJSON(strJson);

    然后在你的 Fragment 中创建一个接收器

    private BroadcastReceiver receiver = new BroadcastReceiver() {
    
    @Override
    public void onReceive(Context context, Intent intent) {
      ArrayList<Exercises> exercises = intent.getExtras().get(MY_KEY);
    
      //or
      //exercises = ParseJSON.ChallengeParseJSON(intent.getStringExtra(MY_KEY));
    
       }
    };
    

    register它在你的onResume

      @Override
     protected void onResume() {
       super.onResume();
       getActivity().registerReceiver(receiver, new IntentFilter(FILTER));
     }
    

    您还需要在 onPause 中使用 getActivity().unregisterReceiver(receiver); 取消注册

    如果有兴趣,您还可以阅读更多相关信息here

    【讨论】:

    • 关于如何连续执行此操作的任何想法?在我的应用程序中,每次值发生变化时,我都需要接收数据。
    • 这是将数据从服务发送到片段的最佳方式吗?还有其他方法吗?您能否提供文档来断言您的答案。谢谢。
    【解决方案2】:

    你可以通过两种方法来做到这一点。

    1. 将数据保存到数据库并以片段的形式获取数据。
    2. 使用广播

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      相关资源
      最近更新 更多