android - 如何在Fragment中调用Activity的onNewIntent?
伊谢尔伦
伊谢尔伦 2017-04-17 16:03:50
0
1
688

最近在做搜索栏相关功能的时候发现onNewIntent只能在activity中重写,如果要把代码放在fragment上要怎么写呢?
fragment中要调用的公共方法 内容是json解析api的数据并动态添加控件
DreamFragment

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sonny.moocalendar.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class DreamFragment extends BaseFragment {
    public final String APPKEY = "38940dc501db16addba8af7128a0b0b4";
    public final String DEF_CHATSET = "UTF-8";
    public final int DEF_CONN_TIMEOUT = 30000;
    public final int DEF_READ_TIMEOUT = 30000;
    public String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, " +
            "like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    private String TAG = "DreamFragment";
    private LinearLayout dreamLayout;

    @Override
    protected void afterCreate(Bundle savedInstanceState) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.content_dream;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().setTitle(R.string.search_title);
        View v = super.onCreateView(inflater, container, savedInstanceState);
        dreamLayout = (LinearLayout) v.findViewById(R.id.dream_layout);
        
        return v;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.options_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                getActivity().onSearchRequested();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void getRequest2() {
        String result = null;
        String url = " http://v.juhe.cn/dream/query";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("key", APPKEY);//应用APPKEY(应用详细页查询)
        params.put("q", "黄金");//梦境关键字,如:黄金 需要utf8 urlencode
        params.put("cid", "");//指定分类,默认全部
        params.put("full", "");//是否显示详细信息,1:是 0:否,默认0

        try {
            result = net(url, params, "GET");
            JSONObject object = new JSONObject(result);
            if (object.getInt("error_code") == 0) {
                Log.d(TAG,object.get("result").toString());
                JSONArray jsonArray = new JSONArray(object.get("result").toString());
                final JSONObject object1 = (JSONObject) jsonArray.get(0);
                Log.d(TAG, object1.get("title") + ":" + object1.get("des"));
                final TextView titleText = new TextView(getActivity());
                final TextView desText = new TextView(getActivity());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            titleText.setText(object1.get("title").toString());
                            desText.setText(object1.get("des").toString());
                            dreamLayout.addView(titleText);
                            dreamLayout.addView(desText);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                Log.d(TAG,object.get("error_code") + ":" + object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "",
                        "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

MainActivity.java

import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


import com.sonny.moocalendar.R;

import com.sonny.moocalendar.fragment.DreamFragment;
import com.sonny.moocalendar.fragment.MainFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string
                .navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //Fragment
        MainFragment mainFragment = new MainFragment();
        DreamFragment dreamFragment = new DreamFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment, mainFragment);
        transaction.commit();
//        handleIntent(getIntent());
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (id == R.id.nav_calendar) {
            // Handle the camera action
        } else if (id == R.id.nav_reminders) {

        } else if (id == R.id.nav_notes) {

        } else if (id == R.id.nav_setting) {

        } else if (id == R.id.nav_oneiromancy) {
            DreamFragment dreamFragment = new DreamFragment();
            transaction.replace(R.id.fragment, dreamFragment);
            transaction.commit();
        } else if (id == R.id.nav_constellation) {

        } else if (id == R.id.nav_festival) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //通过某个方法,请求检索你的数据
            Toast.makeText(MainActivity.this, "你要查询的是:" + query, Toast.LENGTH_SHORT).show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    DreamFragment.getRequest2();
                    //报错:Error:(144, 34) 错误: 无法从静态上下文中引用非静态 方法 getRequest2()
                }
            }).start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

BaseFragment.java 无关紧要

public abstract class BaseFragment extends Fragment {
    protected View mRootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == mRootView) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
        }

        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable
                                  Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        afterCreate(savedInstanceState);
    }

    protected abstract int getLayoutId();

    protected abstract void afterCreate(Bundle savedInstanceState);
}

但是如果单单是在activity的onNewIntent中调用的话,android studio就提示我要设置getRequest2为static..设置了之后里面的getActivity又划红线了唉╮(╯▽╰)╭
接口回调也不知道怎么写..想问问这种问题一般怎么解决会比较好,另外这种动态添加View的方式会不会很粗糙?

补充了其他代码..报错实在没看懂

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
Ty80

It’s strange that the prompt is static. I tried to write a test myself, but there was no prompt.
Could it be a problem with the net method?
Please post more codes.

In addition, there are 2 points:

  1. In Android development, use Log instead of System.out.println to view data output. At least in terms of feature richness, the former can have tags.

  2. Regarding dynamically adding controls, it is recommended to use the method of controlling the visibility attribute. Because if you add them directly, you need to write more attributes in code. If titleText and desText are often displayed, but only after the network is loaded, then it is simpler and more effective to set them as gone at first and then as visible.


DreamFragment.getRequest2();
The reason for the error: DreamFragment is a class, not a variable.
Modification method:
Declare DreamFragment as a member variable inside Activity in onCreate.

//DreamFragment dreamFragment = new DreamFragment();
mDreamFragment = new DreamFragment();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template