从Activity中调用Fragment中的AsyncTask

时间:2017-02-26 16:31:23

标签: android android-fragments android-asynctask

在我的应用程序中,我的main_activity包含if($imgSize < 5000000)FrameLayout

Fragment

我需要拨打public class Fragment1 extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, container, false); return view; } public class StartAsyncTask extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... voids) { Log.e("startAsyncTask", "start"); return null; } } } 中的AsyncTask, 所以我用:

MainActivity

但它不起作用。 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); Fragment1 fragment1 = new Fragment1(); fragmentTransaction.replace(R.id.fragment, fragment1).commit(); new Fragment1.StartAsyncTask().execute(); } 为红色,(不包含类)错误。

3 个答案:

答案 0 :(得分:2)

你可以这样做,从你的MainActivity你可以间接调用你的AsyncTask

ublic class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    BlankFragment fragment1 = new BlankFragment();
    fragmentTransaction.replace(R.id.activity_main,    fragment1).commit();
    fragment1.startASycnc();
    }
}

你的片段看起来像这样:

public class BlankFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

public void startASycnc() {
    new StartAsyncTask().execute();
}

public class StartAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        Log.e("startAsyncTask", "start");
        return null;
       }
    }
   }

答案 1 :(得分:0)

StartAsyncTaskFragment的内部类,而不是方法。如果你真的需要在Fragment中触发某些事情,那么让它公开一个公共方法,该方法采取适当的行动,而不是让一个类在它之外的方法知道它的内部。

答案 2 :(得分:0)

这就是我的做法

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

    @Override
    protected String doInBackground(String... params) {

        while (true) {
            System.out.println("working 1");

            if (getActivity() != null) {
                System.out.println("working 2");
                if (FirebaseAuth.getInstance().getCurrentUser() != null) {

                    System.out.println("working 3");

                    DatabaseReference reference = FirebaseDatabase.getInstance().getReference(Comman.FRIENDS_REF).child(FirebaseAuth.getInstance().getCurrentUser().getUid());

                    reference.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


                            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                                final FriendsModel friendsModel = snapshot.getValue(FriendsModel.class);

                                DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference(Comman.PUBLIC_LOCATION_REF).child(friendsModel.getFrienduid()).child("l");

                                reference1.addListenerForSingleValueEvent(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull final DataSnapshot dataSnap) {

                                        if (dataSnap.hasChild("0")) {


                                            Picasso.get().load(friendsModel.getFriendimgurl())
                                                    .into(new Target() {
                                                        @Override
                                                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                                                            if (markerFriend != null) {
                                                                markerFriend.remove();
                                                            }

                                                            double lat = (double) dataSnap.child("0").getValue();
                                                            double lng = (double) dataSnap.child("1").getValue();

                                                            System.out.println("lat = " + lat);
                                                            System.out.println("Your Friend " + friendsModel.getFriendname() + " is Here");


                                                            MarkerOptions markerOptions = new MarkerOptions();
                                                            markerOptions.position(new LatLng(lat, lng));


                                                            markerOptions.icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(bitmap)));


                                                            markerOptions.title("Your Friend " + friendsModel.getFriendname() + "");
                                                            // markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_person_marker));
                                                            markerFriend = mMap.addMarker(markerOptions);


                                                            if (isSharingValue.equals("true")) {

                                                                setupMapIfNeeded();
                                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


                                                                    if (checkLocationPermission() && checkLocation())//check whether location service is enable or not in your  phone
                                                                    {
                                                                        setupLocation();
                                                                    }


                                                                } else {


                                                                    if (checkLocation())//check whether location service is enable or not in your  phone
                                                                    {
                                                                        setupLocation();
                                                                    }
                                                                }
                                                            }


                                                        }

                                                        @Override
                                                        public void onBitmapFailed(Exception e, Drawable errorDrawable) {


                                                            double lat = (double) dataSnap.child("latitude").getValue();
                                                            double lng = (double) dataSnap.child("longitude").getValue();

                                                            System.out.println("lat = " + lat);
                                                            System.out.println("You Friend " + friendsModel.getFriendname() + " is Here");

                                                            MarkerOptions markerOptions = new MarkerOptions();
                                                            markerOptions.position(new LatLng(lat, lng));
                                                            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                                                            markerOptions.title("You Friend " + friendsModel.getFriendname() + "");
                                                            // markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_person_marker));
                                                            mMap.addMarker(markerOptions);


                                                        }

                                                        @Override
                                                        public void onPrepareLoad(Drawable placeHolderDrawable) {

                                                        }
                                                    });


                                            for (int i = 0; i < placesArrayList.size(); i++) {

                                                LatLng latLngplace = new LatLng(Double.parseDouble(placesArrayList.get(i).getPlacelat()), Double.parseDouble(placesArrayList.get(i).getPlacelng()));
                                                queryForFriendInThePlace(latLngplace, (Double.parseDouble(placesArrayList.get(i).getPlaceradius()) / 1000), friendsModel.getFrienduid(), friendsModel.getFriendname(), placesArrayList.get(i).getPlacename());

                                            }

                                        } else {
                                            System.out.println("result is: nofriend online");
                                        }

                                    }


                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                    }
                                });


                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });


                    try {
                        Thread.sleep(4000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    //   return "Executed";

                }
            }
        }
    }

    @Override
    protected void onPostExecute(String result) {


    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

您只需编写即可执行

new MyFriendsLocationUpdate().execute("");