LocalBroadcastManager多次发送数据

时间:2017-06-15 05:23:18

标签: android android-fragments android-intent android-broadcast android-broadcastreceiver

我有一个片段,当用户输入一个链接并点击按钮时,会启动一个服务来处理链接并抓取图像或视频,如果网址上有任何内容...

但我的问题是同样的下载次数超过2到3次.. 这是片段 -

public class FragmentTwo extends Fragment {

FloatingActionButton btn;
EditText et1;
String profilname;
ProgressDialog pd;
private ArrayList<Long> mDownloadIds = new ArrayList<>();



    public FragmentTwo() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
         View rootView = inflater.inflate(R.layout.fragment_two,container, false);

getActivity().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        LocalBroadcastManager.getInstance(getActivity())
            .registerReceiver(myReceiver, new IntentFilter(Constants.BROADCAST_ACTION));


FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.button1);
    EditText et1 = (EditText) rootView.findViewById(R.id.editText1);


 pd = new ProgressDialog(getActivity());
        pd.setMessage("Let us Check");
        pd.setIndeterminate(true);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);

btn.setOnClickListener(new OnClickListener() {              
@Override               
public void onClick(View v) { 
EditText et1 = (EditText)

getView().findViewById(R.id.editText1); 
profilname = et1.getText().toString();

((InputMethodManager) getActivity().getSystemService("input_method"))                   .hideSoftInputFromWindow(et1.getWindowToken(), 0);                  

profilname.replace("https://www.instagram.com/","https://instagram.com/");

if (profilname.trim().equals("")){ 
Toast.makeText(getActivity(), "Link is Blank!", 0) 

.show(); 
}

else if(isNetworkAvailable()){

Toast.makeText(getActivity(), profilname, 0) 
.show(); 
    DownloaderService.startActionFoo(getActivity(), profilname);
pd.show();
}

else{
Toast.makeText(getActivity(), "Network Error", 0) 
.show(); 
}
}       
    });



return rootView;
    }

    private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE );
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }


    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ContentValues contentValues = intent.getParcelableExtra(Constants.MEDIA_INFO);
            String mediaUrl = contentValues.getAsString(Constants.MEDIA_URL);
            String mediaName = contentValues.getAsString(Constants.MEDIA_NAME);
            pd.dismiss();
            download(mediaUrl, mediaName);

            EditText et1 = (EditText)

getView().findViewById(R.id.editText1); 
et1.setText("");
        }
    };

    private BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long enqueueId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (mDownloadIds.contains(enqueueId)) {
               /* if (mBtnDownload.getVisibility() == View.VISIBLE) {
                    mBtnDownload.setVisibility(View.GONE);
                }*/
                getActivity().getLoaderManager().getLoader(0);
            }
        }
    };


    public void onDestroy() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(myReceiver);
        getActivity().unregisterReceiver(onComplete);
        super.onDestroy();
    }

    private void download(String url, String fileName) {

        File root = Environment.getExternalStorageDirectory();
        File myDir = new File(root + "/MCD/");
        myDir.mkdirs();

           DownloadManager mDownloadManager = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
        if (!doesRequestExist(mDownloadManager, url)) {
           /* boolean allowedOverMetered = mSettings.getBoolean(PREF_KEY_NETWORK, true);*/
            int networkType = NETWORK_WIFI | NETWORK_MOBILE;
        /*    if (allowedOverMetered) {
                networkType = NETWORK_WIFI | NETWORK_MOBILE;
            }*/
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setTitle(fileName);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(root + "/MCD/", fileName);
            request.setAllowedNetworkTypes(networkType);

            long id = mDownloadManager.enqueue(request);
            mDownloadIds.add(id);
        }
    }

    private boolean doesRequestExist(DownloadManager downloadManager, String url) {
        boolean result = false;
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL
            | DownloadManager.STATUS_PENDING
            | DownloadManager.STATUS_RUNNING);
        Cursor cursor = downloadManager.query(query);
        while (cursor.moveToNext()) {
            int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
            String uri = cursor.getString(uriIndex);
            if (uri.equals(url)) {
                result = true;
                break;
            }
        }
        cursor.close();
        return result;
    }

    }

这是下载服务 -

public class DownloaderService extends IntentService {
    private static final String ACTION_FOO = "com.parrotainment.media.downloader.action.FOO";

    private static final String EXTRA_URL = "com.parrotainment.media.downloader.extra.URL";

    public DownloaderService() {
        super("DownloaderService");
    }

    public static void startActionFoo(Context context, String url) {
        Intent intent = new Intent(context, DownloaderService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_URL, url);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String url = intent.getStringExtra(EXTRA_URL);
                handleActionFoo(url);
            }
        }
    }

    private void handleActionFoo(String urlStr) {
        try {
            ContentValues mediaInfo = new ContentValues();
            Document doc = Jsoup.connect(urlStr).timeout(5000).get();
            Document content = Jsoup.parse(doc.toString());
            String videoUrl = content.getElementsByAttributeValue("property","og:video")
                    .attr("content");
            String title = content.getElementsByAttributeValue("property","og:title")
                    .attr("content").replaceAll("[^a-zA-Z0-9\\u4E00-\\u9FA5\\s]","");

            if (!videoUrl.isEmpty()) {
                String videoName = title + ".mp4";
                mediaInfo.put(Constants.MEDIA_NAME, videoName);
                mediaInfo.put(Constants.MEDIA_URL, videoUrl);
            } else {
                String imgUrl = content.getElementsByAttributeValue("property","og:image").attr("content");
                String imgName = title + ".jpg";
                mediaInfo.put(Constants.MEDIA_NAME, imgName);
                mediaInfo.put(Constants.MEDIA_URL, imgUrl);
            }
            Intent intent = new Intent(Constants.BROADCAST_ACTION);
            intent.putExtra(Constants.MEDIA_INFO, mediaInfo);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

&安培;常数 -

public final class Constants {
    public static final String BROADCAST_ACTION = "com.parrotainment.media.downloader.BROADCAST";
    public static final String MEDIA_INFO = "com.parrotainment.media.downloader.MEDIA_INFO";
    public static final String MEDIA_NAME = "com.parrotainment.media.downloader.MEDIA_NAME";
    public static final String MEDIA_URL = "com.parrotainment.media.downloader.MEDIA_URL";
}

1 个答案:

答案 0 :(得分:0)

只是检查oReceive中的数据可能有所帮助。像这样:

ChannelHandler

// }