从json加载视频链接

时间:2018-10-23 04:48:37

标签: android arrays json android-studio live-streaming

我有一个exoplayer示例,该示例从链接播放Iptv实时流。 完整的代码只有1个Java + xml活动,现在我想使用json文件加载项目“链接”列表,当我单击项目时,将我带到exoplayer活动。 所以我这样做了:
1。。我下载了json代码,并根据需要使用 title + discription (描述为链接)对其进行了自定义。
我想单击描述项,以播放其视频链接,请提供任何帮助:

Json文件

{
"contacts": [
    {

            "title": "video 1",
            "discription": "http://117.196.231.0:86/hls/10.m3u8"
    },
    {

            "title": "video 2",
            "discription": "http://117.196.212.0:86/hls/54.m3u8"
    }
]
}

Samlpe活动:

public class normal_iptv extends Activity implements VideoRendererEventListener {

TextView btn_refrsh;
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;

Uri mp4_Video_link = Uri.parse("http://117.196.231.0:86/hls/10.m3u8");

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

    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
    TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

    final LoadControl loadControl = new DefaultLoadControl();

    player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
    simpleExoPlayerView = new SimpleExoPlayerView(this);
    simpleExoPlayerView = findViewById(R.id.player_view);

    //Set media controller
    simpleExoPlayerView.setUseController(true);
    simpleExoPlayerView.requestFocus();

    // Bind the player to the view.
    simpleExoPlayerView.setPlayer(player);

    DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
    //Produces DataSource instances through which media data is loaded.
    DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeterA);

    //FOR LIVESTREAM LINK:
    MediaSource videoSource = new HlsMediaSource(mp4_Video_link, dataSourceFactory, 1, null, null);
    final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);

    // Prepare the player with the source.
    player.prepare(loopingSource);

    player.addListener(new ExoPlayer.EventListener() {
        @Override
        public void onTimelineChanged(Timeline timeline, Object manifest) {
        }

        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
        }

        @Override
        public void onLoadingChanged(boolean isLoading) {
        }

        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        }

        @Override
        public void onRepeatModeChanged(int repeatMode) {
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            player.stop();
            player.prepare(loopingSource);
            player.setPlayWhenReady(true);
        }

        @Override
        public void onPositionDiscontinuity() {
        }

        @Override
        public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
        }
    });

    player.setPlayWhenReady(true);
    player.setVideoDebugListener(this);
}

@Override
public void onVideoEnabled(DecoderCounters counters) {

}

@Override
public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {

}

@Override
public void onVideoInputFormatChanged(Format format) {

}

@Override
public void onDroppedFrames(int count, long elapsedMs) {

}

@Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {

}

@Override
public void onRenderedFirstFrame(Surface surface) {

}

@Override
public void onVideoDisabled(DecoderCounters counters) {

}


@Override
protected void onStop() {
    super.onStop();

}

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

}

@Override
protected void onResume() {
    super.onResume();

}

@Override
protected void onPause() {
    super.onPause();

}

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

}

json活动

/// json file link
 private static String url = "https://www.dropbox.com/s/loleo014140mifa";

ArrayList<HashMap<String, String>> contactList;
ListAdapter adapter;
private String TAG = normal_json_main.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;

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

    contactList = new ArrayList<>();
    lv = findViewById(R.id.list);
    new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(normal_json_main.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
    normal_json_HttpHandler sh = new json_HttpHandler();

     /// Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

  if (jsonStr != null) {
   try {
 JSONObject jsonObj = new JSONObject(jsonStr);

    /// Getting JSON Array node
 JSONArray contacts = jsonObj.getJSONArray("contacts");

   /// looping through All Contacts
  for (int i = 0; i < contacts.length(); i++)
   JSONObject c = contacts.getJSONObject(i);

 String video_title = c.getString("title");
 String video_discription = c.getString("discription");


  /// tmp hash map for single contact
      HashMap<String, String> contact = new HashMap<>();

  /// adding each child node to HashMap key => value
      contact.put("title", video_title);
      contact.put("discription", video_discription);

  /// adding contact to contact list
       contactList.add(contact);
                }
            } catch (final JSONException e) {
   Log.e(TAG, "Json parsing error: " + e.getMessage());
      runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
          }
       });

      }
        } else {
       Log.e(TAG, "Couldn't get json from server.");
        runOnUiThread(new Runnable() {
         @Override
          public void run() {
                    Toast.makeText(getApplicationContext(), "Something Went wrong!", Toast.LENGTH_LONG).show();
          }
     });

    }

   return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();


  adapter = new SimpleAdapter(normal_json_main.this, contactList,R.layout.normal_json_list_item, new String[]{"title", "discription"}, new int[]{R.id.vid_title,
                R.id.vid_disc});

  lv.setAdapter(adapter);

  lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ///=== on item click play the video

        }

    });

}

}
}

1 个答案:

答案 0 :(得分:0)

您应使用此代码来检索列表中的选定项目:

HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPostion(position);
String title = item.get("title");
String discription = item.get("discription");

,然后通过意图将所选链接传递到您的玩家活动。

在您的json活动中:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPostion(position);
if(item!=null){
String title = item.get("title");
String discription = item.get("discription");
Intent intent = new Intent(this,PlayerActivity.class);
intent.putExtras("link",discription);
startActivity(intent)
    }
});

在玩家活动中:

protected void onCreate(Bundle savedInstanceState) { 
//Other codes
Bundle extras = getIntent().getExtras();
if(extras != null) {
String link= extras.getString("link");
    mp4_Video_link = Uri.parse(link)
}
}