android - 在后台将数据从广播接收器更新到片段列表视图
问题描述
我是 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);
}
}
解决方案
片段不能独立工作,必须在一个活动中。
所以第一步是创建一个活动并将你的片段放入其中。那么您必须以意图进入广播接收器的方式开始该活动。类似的东西:
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));
推荐阅读
- javascript - 使用Javascript将变量作为sqlite列名插入?
- matlab - 如果 A 是 B 的向量子集,我如何在 MATLAB 中找到 B 中 A 的索引?
- java - Java RMI NotBoundException?
- java - Java - 当我运行我的公式计算器程序时,即使选择了另一个形状,它也会默认询问“圆的半径是多少”
- flask - 在 Eve check_auth 方法中访问 Flask 请求对象
- loops - 自动将递归转换为迭代
- c++ - basic_string 到 basic_string_view 隐式转换...呃,为什么?
- javascript - 将节点 api 部署到 heroku 时遇到问题
- java - 如何获取 GPS 时间或网络时间,location.getTime() 返回错误的设备日期和时间
- c# - 如何在 UWP/C# 中使用 svg 文件资源设置 AppBarButton 图标