Воспроизведение видео списка воспроизведения с использованием JSON - PullRequest
0 голосов
/ 22 октября 2018

Я новичок в Android и я в стеке:
У меня есть действие с несколькими кнопками "каждая кнопка имеет ссылку на видео" , когда я нажимаю на нее, она переходит к player_activityчтобы воспроизвести его.
Так что вместо того, чтобы ставить несколько кнопок, я хотел бы использовать файл json, чтобы вывести список видео и прочитать их.

1) Я загрузил код json инастройте его по мере необходимости.
2) У Json "Title + Discription работает отлично".
3) Я добавил URL в json "Я просто положил его туда",

Теперь я хочу, чтобы этот URL работал во время чтения json, и когда я щелкаю по любому элементу, он читает ссылку на него.

Вот мой файл json :

{
"contacts": [
    { 
            "title": "video Title 1",
            "discription": "discription here"
            "link" :"http://117.196.231.0:86/hls/10.m3u8"
    },
     {

            "title": "video Title 2",
            "discription": "discription here"
            "link" :"http://117.196.231.0:86/hls/10.m3u8"
    }
]
}

Вот действие со ссылками :

final String link_1 = "http://117.196.231.0:86/hls/10.m3u8";
final String link_2 = "http://117.196.231.0:86/hls/10.m3u8";
final String link_3 = "http://117.196.231.0:86/hls/10.m3u8";


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


    Button btn1 = findViewById(R.id.iptv1);
    Button btn2 = findViewById(R.id.iptv2);


    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            intent = new Intent(getApplicationContext(), activity_VideoPlayer.class).setData(Uri.parse(link_1))
                    .putExtra(activity_VideoPlayer.CONTENT_ID_EXTRA, 0)
                    .putExtra(activity_VideoPlayer.CONTENT_TYPE_EXTRA, DemoUtil.TYPE_HLS);
            startActivity(intent);

        }
    });


    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(getApplicationContext(), activity_VideoPlayer.class).setData(Uri.parse(link_2))
                    .putExtra(activity_VideoPlayer.CONTENT_ID_EXTRA, 0)
                    .putExtra(activity_VideoPlayer.CONTENT_TYPE_EXTRA, DemoUtil.TYPE_HLS);
            startActivity(intent);

        }
    });  
   }
 }

jsonОсновная деятельность :

private static String url = "https://www.dropbox.com/s/q8rttgi4vl8a6at/help_here.json?dl=0";
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 normal_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);

    }
}
}

JSON HttpHandler :

private static final String TAG = normal_json_HttpHandler.class.getSimpleName();

public normal_json_HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

Любая помощь будет высоко ценится.Спасибо

1 Ответ

0 голосов
/ 22 октября 2018

Один из способов - задать продолжительность видео в секундах в одном и том же json:

{
"contacts": [
    { 
        "title": "video Title 1",
        "discription": "discription here"
        "link" :"http://117.196.231.0:86/hls/10.m3u8"
        "duration" :"15"
    },
    {

        "title": "video Title 2",
        "discription": "discription here"
        "link" :"http://117.196.231.0:86/hls/10.m3u8"
        "duration" :"30"
    }
    ]
}

Когда вы воспроизводите первое видео, вы планируете запускать / воспроизводить второе после того, как время первого видеопередано с использованием таймера:

startTimer(content.getDuration());

Вы можете установить таймер, подобный этому, чтобы убедиться, что предыдущий уничтожен:

public void startTimer(float delay) {
    float intDelay = delay * 1000;
    //set a new Timer
    if (mainTimer != null) {
        mainTimer.cancel();
        mainTimer.purge();
        mainTimer = null;
    }

    mainTimer = new Timer();

    mainTimer.schedule(new TimerTask() {
        @Override
        public void run() {

            h.post(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            playContent();
                        }
                    });
                }
            });
        }
    }, (int) intDelay);
}

Метод playContent () будет отвечать только установкойУРИ как видеодатчик.

...