首页 > 解决方案 > 在后台将数据从广播接收器更新到片段列表视图

问题描述

我是 android 开发的新手,我正在制作这个接收消息的应用程序,onReceive. 我想更新 a 中的那些数据,ListView并且fragment更新应该在后台进行。Broadcast Receiver 全局注册

@Override
    public void onReceive(Context context, Intent intent) {
        Hover.initialize(context);
       /* IncomingSMSReceiver incomingSMSReceiver = new IncomingSMSReceiver();
        incomingSMSReceiver.onReceive(context,intent);*/
        String uuid = intent.getStringExtra("response_message");
        Log.d(TAG, " " + uuid);

        if (intent.hasExtra("transaction_extras")) {
            HashMap t_extras = (HashMap) intent.getSerializableExtra("transaction_extras");
            /*if (t_extras.containsKey("confirmCode")) {
                String confirmationCode = t_extras.get("confirmCode").toString();
                Log.d(TAG, " "+confirmationCode);
            }*/
            if (t_extras.containsKey("Tsh")) {
                String balance = t_extras.get("Tsh").toString();
                Log.d(TAG," "+balance);

                Bundle bundle = new Bundle();
                bundle.putString("id", uuid);
                bundle.putString("message", balance);
                FragmentHistory fragmentHistory = new FragmentHistory();
                fragmentHistory.setArguments(bundle);

            }
        }

    }

分段

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       // return inflater.inflate(R.layout.fragment_history, container,false);
        View view = inflater.inflate(R.layout.fragment_history, container, false);
       /* mRecyclerView =(RecyclerView) view.findViewById(R.id.recyclerView_history);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(true);
        configAdapter();*/

    dataSaver.initializeDataSaver(getActivity());

   // listScore = view.findViewById(R.id.list);
    return view;

}

@Override
public void onActivityCreated( Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //dataSaver.setViewList("Hello", "Hola");
    dataSaver.getDataList(this.getActivity());

    /*try {
        Bundle bundle = getActivity().getIntent().getExtras();
        dataSaver.setViewList(bundle.getString("id"), bundle.getString("message"));
    } catch (Exception e) {
        e.printStackTrace();
    }*/

}

@Override
public void onResume() {
    super.onResume();
    dataSaver.getDataList(this.getActivity());
}

@Override
public void onPause() {
    super.onPause();
    Bundle arguments = getArguments();
    if (arguments != null) {
        handleArguments(arguments);
    }
    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        handleExtras(extras);
    }
}

@Override
public void onStop() {
    super.onStop();
    Bundle arguments = getArguments();
    if (arguments != null) {
        handleArguments(arguments);
    }
    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        handleExtras(extras);
    }
}



@Override
public void onDestroyView() {
    super.onDestroyView();
    Bundle arguments = getArguments();
    if (arguments != null) {
        handleArguments(arguments);
    }
    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        handleExtras(extras);
    }
    Toast.makeText(getActivity(), "Destroyed", Toast.LENGTH_LONG).show();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Bundle arguments = getArguments();



}

private void handleArguments(Bundle arguments) {
    // TODO
    try {
        String id =arguments.getString("id");
        String message = arguments.getString("message");
        dataSaver.setViewList(id, message);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

ListView 适配器

private ArrayList<TransDetails> scores;
    TransDetails transDetails;
    private MySharedPreference sharedPreference;
    private ListView listScore;
    private HashSet<String> scoreset;
    private Gson gson;

public void initializeDataSaver(Activity activity){

    transDetails = new TransDetails();
    scores = new ArrayList<>();
    gson = new Gson();
    sharedPreference = new MySharedPreference(activity);
    getHighScoreListFromSharedPreference();
}

/*public void setGson(Gson gson) {
    this.gson = gson;
}*/

public Gson getGson() {
    return gson;
}

/*public void setActivity(Activity activityf){
    activityf = getActivity();
}

public Activity getActivity(){
    return getActivity();
}*/




public void getHighScoreListFromSharedPreference() {
    //retrieve data from shared preference
    String jsonScore = sharedPreference.getHighScoreList();
    Type type = new TypeToken<List<TransDetails>>(){}.getType();
    scores = gson.fromJson(jsonScore, type);

    if (scores == null) {
        scores = new ArrayList<>();
    }
}

public void saveScoreListToSharedpreference(ArrayList<TransDetails> scoresList) {
    //convert ArrayList object to String by Gson
    String jsonScore = gson.toJson(scoresList);

    //save to shared preference
    sharedPreference.saveHighScoreList(jsonScore);
}

public void upDateList(final String id, final String message){
    transDetails.setId(id);
    transDetails.setId(message);
    scores.add(0, transDetails);
}

public void setViewList(String trans_id, String trans_amount){
    if (trans_id != null) {


        transDetails.setId(trans_id);
        transDetails.setMessage(trans_amount);
        scores.add(0,transDetails); //add to scores list
        saveScoreListToSharedpreference(scores);
    }

}

public void getDataList(Activity activity){

    listScore = activity.findViewById(R.id.list);
    if (scores.size() == 0) {
        Toast.makeText(activity, "No data in sharedPreferences", Toast.LENGTH_SHORT).show();
    } else {
        getHighScoreListFromSharedPreference();
        //get data
        //set adapter for listview and visible it
        ListViewAdapter adapter = new ListViewAdapter(activity,  scores);
        listScore.setAdapter(adapter);

    }

}

标签: androidandroid-fragments

解决方案


片段不能独立工作,必须在一个活动中。

所以第一步是创建一个活动并将你的片段放入其中。那么您必须以意图进入广播接收器的方式开始该活动。类似的东西:

context.startActivity(new Intent(this,ListActivity.class));

另一个问题是,当收到新消息时,您的 startActivity 将再次启动并重复创建。为避免此问题,您必须以这种方式向 Intent 添加标志:

context.startActivity(new Intent(this,ListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

此标志是为了避免重新创建活动并将现有活动放在前面。这样,您传递给它的意图和数据将在onNewIntent()活动方法中接收,您可以在那里处理您的数据。

因此,您必须从 bundle 开始,而不是片段中的 setArguments:

context.startActivity(new Intent(this,ListActivity.class).putExtras(bundle).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

推荐阅读