Search code examples
android-fragmentsandroid-serviceandroid-fragmentactivity

Method worked in Activity but not in a fragment


i converted my activity to a fragment, the method network_reinit_activity worked fine before, but when i run it in fragment it wont, this is the method:

private final Context c = getActivity();

private void network_reinit_activity() {

    new Thread(new Runnable() {
        @Override
        public void run() {
            Activity mainAct = (Activity)c;
            Intent new_i = new Intent(getActivity(), NavigationActivity.class);
        mainAct.finish();
        Intent srv_i = new Intent(c, RadioStreamService.class);
        srv_i.putExtra("RS_STREAM_URL", RS_STREAM_URL);
        getActivity().stopService(srv_i);
        if(isInForeground)
    //          startActivity(new_i);
        }
    }).run();


}

Solution

  • fragment does not finish, the activity finish, please see below code

    new Thread(new Runnable() {
            @Override
            public void run() {
                Activity mainAct = (Activity)c;
                Intent new_i = new Intent(getActivity(), NavigationActivity.class);
                 getActivity().onBackPressed()   // to finish fragment
                 Intent srv_i = new Intent(c, RadioStreamService.class);
                 srv_i.putExtra("RS_STREAM_URL", RS_STREAM_URL);
                 getActivity().stopService(srv_i);
                 if(isInForeground)
                 //          startActivity(new_i);
                 }
        }).run();