如何覆盖媒体播放器片段中的后退按钮

时间:2014-07-21 12:42:31

标签: java android android-fragments

我已经尝试覆盖android中的后退按钮,但到处都有错误。当我点击片段中的后退按钮时,我想停止媒体播放器。我在谷歌搜索但是没有媒体播放器的例子仅用于webview有很多例子

STOREFRAGMENT.java

public class StoreFragment extends Fragment {
    View rootView;
    ImageView imageview;
    String file_url;

    final MediaPlayer mp = new MediaPlayer();
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
private int keyCode;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.store_home, container, false);
    return rootView;
}

@Override

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                String url = "http://localhost/Android_App/storehome.php";

                try {
                    JSONArray data = new JSONArray(getJSONUrl(url));

                    HashMap<String, String> map;

                    for (int i = 0; i < data.length(); i++) {
                        JSONObject c = data.getJSONObject(i);

                        map = new HashMap<String, String>();
                        map.put("name", c.getString("name"));

                        map.put("price", c.getString("price"));
                        map.put("image", c.getString("image"));

                        MyArrList.add(map);
                    }

                } catch (JSONException e) {

                    e.printStackTrace();
                } catch (Exception e) {

                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
                gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
            }

        }.execute();

   }      

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      @Override
    protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              bmImage.setImageResource(android.R.drawable.ic_menu_report_image);
          }
          return mIcon11;
      }

      @Override
    protected void onPostExecute(Bitmap res) {
            bmImage.setImageBitmap(res);
      }
    }


class ImageAdapter extends BaseAdapter 

{
    private Context context;
    public ImageView imageView;
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list) 
    {   
        context = c;

        MyArr = list;
    }

    @Override
    public int getCount() {

        return MyArr.size();
    }

    @Override
    public Object getItem(int position) {

        return position;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.store_home_gridview_row, null); 
        }






        Button play_grid = (Button)convertView.findViewById(R.id.play_gridview);
        play_grid.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    mp.reset();
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mp.setDataSource(tv_hidden.getText().toString());

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) { 
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {   
                    e.printStackTrace();
                }
                mp.start();

            }

        });

        Button stop_grid = (Button)convertView.findViewById(R.id.stop_gridview);
        stop_grid.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mp.isPlaying())
                {
                    mp.stop();
                    mp.reset();
                }   
            }

        });

        return convertView;
    }
    }



 /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try 
        {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) 
            { 
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) 
                {
                    str.append(line);
                }
            }   
            else 
            {
                Log.e("Log", "Failed to download file..");
            }
        } 
        catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        return str.toString();
    }
}

我添加了此代码,但收到错误

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mp.stop(); //stop media player
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

如果我取出覆盖然后错误会消失,但后退按钮不起作用,任何人都可以告诉我如何在片段内添加方法

1 个答案:

答案 0 :(得分:2)

这是答案: 完美的工作.. {{3P> 在doBack()函数中

只需将其更改为mp.stop()。

希望它有所帮助。