片段在背景中工作

时间:2015-07-16 17:09:13

标签: java android

嘿,伙计们我正在制作一个网络浏览器,并且可以使用可转换的标签 我想如果有人加载网页并打开新标签,旧标签应该继续加载,最后它可以保存自己

问题是如果创建新标签,旧标签会忘记它们正在加载的内容以及何时选择它们开始加载主页(它在我的一个标签片段的oncreateView中)

请帮助我尽快完成

任何帮助将不胜感激

感谢你们很多人

这是我的片段

package com.android.shubham.muffinbrowserv10;

 //suppose all imports are here
public class Myfragment extends Fragment implements                                       EditText.OnEditorActionListener , ImageButton.OnClickListener
{
    Date pagedate ;
static EditText url;
public static WebView web;
String input =" ";
String Url;
String previousInput = " ";
ProgressBar pro;
ImageButton reload_cancel , refresh , Forward;
static File filesDir;
static ArrayList<String> sb;
Activity myact;

public static Boolean incognitoBool = false , noTabBool = false;

static String homePage = "https://www.google.com";

@Override
public void onStart() {
    super.onStart();




}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());


    Settings.setZoomButtons(settings.getBoolean(SettingActivity.any_zoom, true));
    Settings.setZoomDrag(settings.getBoolean(SettingActivity.two_finger_zoom , true));
    Settings.setJavachk(settings.getBoolean(SettingActivity.java_script, true));



   noTabBool = settings.getBoolean(SettingActivity.no_tab , false);
    Myfragment.homePage = settings.getString(SettingActivity.home_page , "https://google.com");
    Myfragment.incognitoBool =  settings.getBoolean(SettingActivity.incognito , false);




}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    myact = getActivity();


    View v =  inflater.inflate(R.layout.activity_bet , container  , false);
    reload_cancel = (ImageButton)v.findViewById(R.id.refresh);
    refresh = (ImageButton)v.findViewById(R.id.refresh);
    Forward = (ImageButton)v.findViewById(R.id.forward);

    refresh.setOnClickListener(this);
    Forward.setOnClickListener(this);
    filesDir = myact.getFilesDir();
    try
    {
        File f = new File(filesDir, "history.txt");
        FileOutputStream fos = new FileOutputStream(f,true);
        OutputStreamWriter opt = new OutputStreamWriter(fos);
        StringBuilder sbhistory = readHistory();
        pagedate = new Date();
        int date = pagedate.getDate();
        int month = pagedate.getMonth();
        int year = pagedate.getYear();
        String ddate = date+"::"+month+"::"+year;
        if(!sbhistory.toString().contains(ddate))
            opt.write("\n"+"!"+ ddate);
        opt.close();
    }catch (Throwable t){
        Toast.makeText(getActivity().getBaseContext() , "Exception in Writing DATE -> " + t , Toast.LENGTH_SHORT).show();
        t.printStackTrace();
    }
    url = (EditText)v.findViewById(R.id.url);
    url.setOnEditorActionListener(this);
    pro= (ProgressBar)v.findViewById(R.id.pro);
    pro.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    web = (WebView)v.findViewById(R.id.web);
    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setSupportZoom(true);
    web.getSettings().setDisplayZoomControls(true);
    web.getSettings().setBuiltInZoomControls(true);
    web.setWebViewClient(new WebViewClient()
                         {
                             @Override
                             public boolean shouldOverrideUrlLoading(WebView view, String url)
                             {
                                 if (url.contains("youtube.com/watch?"))
                                 {
                                     loadpage(url , 3);
                                     return false;
                                 }
                                 else
                                 {
                                     loadpage(url, 1);
                                     return true;
                                 }
                             }
                         }
    );

    String intent_url = getActivity().getIntent().getStringExtra("openPageKey");
    if(intent_url == null )
        loadpage(homePage , 1);
    else
        loadpage(intent_url, 1);


    return v;
}
public void setURL(String web_url)
{
    this.url.setText(web_url);

}
@Override
public void onResume()
{
    this.url.setText(web.getUrl());
    web.getSettings().setDisplayZoomControls(Settings.getZoomDrag());//opposite by mistake
    web.getSettings().setSupportZoom(Settings.getZoomButtons());

    web.getSettings().setJavaScriptEnabled(Settings.getJavachk());

    super.onResume();
}






public void loadpage(String url , int val)
{
    switch (val){
        case 1://///////////////////////////////case 1 direct website loading
            Url = url;
            web.loadUrl(Url);
            reload_cancel.setImageResource(R.drawable.cancel);
            break;

        case 2:////////////////////////////////case 2 inbuilt webKit functions
            switch (url)
            {
                case "goBack":
                    web.goBack();
                    break;
                case "goForward":
                    web.goForward();
                    break;
                case "reload":
                    web.reload();
                    break;
            }
            break;
        case 3://////////////////////////////case 3 using intent to load stuff
            startActivity(new Intent(Intent.ACTION_VIEW , Uri.parse(url)));
    }
    new AsyncTask<Void , Void, Void>(){
        @Override
        protected Void doInBackground(Void... params)
        {
            while(pro.getProgress() < 100) publishProgress();

            if (!incognitoBool)
            writeHistory(Url);

            return null;
        }
        @Override
        protected void onPreExecute()
        {
            Myfragment.this.url.setTextColor(Color.RED);
            pro.setProgress(0);
            pro.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Void aVoid)
        {
            pro.setVisibility(View.INVISIBLE);
            Myfragment.this.url.setTextColor(Color.BLUE);
            Myfragment.this.url.setText(web.getUrl());
            reload_cancel.setImageResource(R.drawable.reload);
        }
        @Override
        protected void onProgressUpdate(Void... params) {
            pro.setProgress(web.getProgress());
        }
    }.execute();
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{

    input = url.getText().toString().trim().toLowerCase();
    int order = 1;
    if(!input.equals(previousInput))
    {
        boolean flag = false;
        if (input.length() >= 4)
        {
            if (input.charAt(input.length() - 3) == '.' || input.charAt(input.length() - 4) == '.')
            {
                flag = true;
                order = 1;
                if (input.contains("www."))
                    input = "https://" + input;
                else
                    input = "https://www." + input;
            }
        }
        if (!flag)
        {

            if (input.contains("youtube.com/watch?"))
            {
                order = 3;
            }
            else
            {
                input = input.replace(" ", "+");
                input = "https://www.google.co.in/search?q=" + input;
                order = 1;
            }
        }

        InputMethodManager mgr = (InputMethodManager) myact.getSystemService(myact.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(url.getWindowToken(), 0);

        previousInput = input;

        loadpage(input, order);
    }
    return false;

}
public void writeHistory(String loadedPage)
{
    try{

        File f = new File(filesDir, "history.txt");
        FileOutputStream fos = new FileOutputStream(f,true);
        OutputStreamWriter opt = new OutputStreamWriter(fos);
        opt.write("\n"+ loadedPage);
        opt.close();
    }catch (Throwable t){
        Toast.makeText(myact.getBaseContext() , "Exception in Writing History -> " + t , Toast.LENGTH_SHORT).show();
    }
}
public static StringBuilder readHistory() throws IOException
{
    File f = new File(filesDir,"history.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    StringBuilder sb = new StringBuilder("");
    while (true) {

        String line = br.readLine();

        if (line == null) break;

        sb.append("\n" + line);
    }



    return sb;

}
public static ArrayList<String> readHistory(Boolean b) throws IOException
{
    if (b) {

        try {
            File f = new File(filesDir, "history.txt");
            FileInputStream fis = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            sb = new ArrayList<String>();
            while (true) {

                String line = br.readLine();

                if (line == null) break;
                sb.add(line);

            }


            return sb;

        }catch(IOException e){}
    }//end of if
    return null;
}
   @Override
    public void onClick(View v)
    {
    switch (v.getId()){
        case R.id.refresh:
            loadpage("reload" , 2);
            break;
        case R.id.forward:
            if (web.canGoForward())loadpage("goForward" , 2);
            else Toast.makeText(myact.getBaseContext() , "Cant go more forward!" , Toast.LENGTH_SHORT).show();
            break;

    }
}
public static void clearcache(){
    web.clearCache(true);
}



}

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用AsyncTask?

当打开新选项卡时,会立即为该片段调用onPause()。并将来自Web代码的加载放在onStart()而不是onCreateView()上。它按原样工作,但onCreateView()用于设置UI。加载的东西应该在onStart()上。

尝试使用AsyncTask,这应该有效。

相关问题