如何在Android中使用线程每秒运行代码

时间:2018-05-19 09:50:15

标签: java android multithreading nullpointerexception android-thread

在我的应用程序中,我希望每隔 120秒运行一次代码,为实现此目的,我使用Thread
以下是我正在使用的代码片段,但它给了我强制关闭错误。

显示此行的错误:

getActivity().runOnUiThread(new Runnable() {}

我的代码:

public class MainReminderFragment extends Fragment {

    @BindView(R.id.mainExplore_noExploreTxt)
    TextView mainExplore_noExploreTxt;
    @BindView(R.id.newsPageLoadLay)
    RelativeLayout newsPageLoadLay;
    @BindView(R.id.toolbarTitleTxt)
    TextView toolbarTitleTxt;
    private Context context;
    public List<Datum> model = new ArrayList<>();
    public ReminderAdapter reminderAdapter;
    private SharedPrefrencesHandler prefrencesHandler;
    private String token = "";
    private LinearLayoutManager layoutManager;
    private MainActivity mainActivity;
    private InterfaceApi api;
    private boolean isRunning = false;
    public ProgressBar mainExplore_progressBar;
    public RecyclerView mainExplore_recyclerView;

    public MainReminderFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main_reminder, container, false);
        //Initialize
        ButterKnife.bind(this, view);
        context = getActivity();
        prefrencesHandler = new SharedPrefrencesHandler(context);
        reminderAdapter = new ReminderAdapter(context, model);
        layoutManager = new LinearLayoutManager(context);
        mainExplore_progressBar = view.findViewById(R.id.mainExplore_progressBar);
        mainExplore_recyclerView = view.findViewById(R.id.mainExplore_recyclerView);
        isRunning = true;
        mainActivity = (MainActivity) getActivity();
        api = ApiClient.getClient().create(InterfaceApi.class);
        //Toolbar name
        toolbarTitleTxt.setText(context.getResources().getString(R.string.reminder));
        //RecyclerView
        mainExplore_recyclerView.setLayoutManager(layoutManager);
        mainExplore_recyclerView.setHasFixedSize(true);
        //Get token
        token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
        //Get data
        getData();
        if (getActivity() != null) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    float i;
                    try {
                        for (i = 0; i <= 100; i++) {
                            getActivity().runOnUiThread(new Runnable() {
                                public void run() {
                                    getData();
                                }
                            });
                            sleep(120000);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
        return view;
    }

    //Get data
    private void getData() {
        try {
            Call<SerialReminderListResponse> call = api.getListSerialReminder(token, "2", sendData(1));

            mainExplore_progressBar.setVisibility(View.VISIBLE);

            call.enqueue(new Callback<SerialReminderListResponse>() {
                @Override
                public void onResponse(Call<SerialReminderListResponse> call, Response<SerialReminderListResponse> response) {
                    if (response.body().getData() != null) {
                        if (response.body().getData().size() > 0) {
                            model.clear();
                            model.addAll(response.body().getData());
                            reminderAdapter.notifyDataSetChanged();
                            mainExplore_recyclerView.setAdapter(reminderAdapter);
                            //Gone no explore
                            mainExplore_noExploreTxt.setVisibility(View.GONE);
                        } else {
                            mainExplore_noExploreTxt.setVisibility(View.VISIBLE);
                            mainExplore_recyclerView.setVisibility(View.GONE);
                        }
                    }

                    mainExplore_progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onFailure(Call<SerialReminderListResponse> call, Throwable t) {
                    mainExplore_progressBar.setVisibility(View.GONE);
                }
            });
        } catch (Exception e) {
        }
    }

在logCat中强制关闭错误:

Process: in.nouri.sevenwatchlist, PID: 7104
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)' on a null object reference
at com.app.test.Fragments.MainPageFrags.MainReminderFragment$1.run(MainReminderFragment.java:136)

3 个答案:

答案 0 :(得分:1)

您的以下代码

getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        getData();
                                    }
                                });
                                sleep(120000);

Replce With:

new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                         getData();
                    }
                }, 120000);

答案 1 :(得分:0)

试试这个。

TextView tv= new TextView(this);
tv.postDelayed(sendData, 1000);

Handler handler = new Handler();

private Runnable sendData=new Runnable(){
public void run(){
    try {
        //prepare and send the data here..
        handler.removeCallbacks(sendData);
        handler.postDelayed(sendData, 12000);    
    }
    catch (Exception e) {
        e.printStackTrace();
    }   
 }
};

答案 2 :(得分:0)

我建议使用ScheduledExecutorService,因为它基于纳米时间,因此更准确。例如:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 1 );

final Runnable r = new Runnable() {
        public void run() {
                // execution point 
        }
};

scheduler.scheduleAtFixedRate(r, 0, 1000, MILLISECONDS);