Back to project page Android-Apps.
The source code is released under:
Apache License
If you think the Android project Android-Apps listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.kniezrec.xbmcgear.connection; //from w w w. j a va2s .c o m import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Base64; import android.util.Log; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.kniezrec.xbmcgear.R; import com.kniezrec.xbmcgear.player.Player; import com.kniezrec.xbmcgear.preferences.Host; import com.kniezrec.xbmcgear.presentation.MainActivity; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Connection { private static final String XBMC_JSONRPC_BOOTSTRAP = "/jsonrpc"; private static final String sVideoPlayer = "video"; private static Connection sConn = null; private final String TAG = "CONNECTION"; private String mBase64Auth = ""; private ProviderService mgearService = null; private String mUrl = null; private Player mPlayer = null; private ScheduledExecutorService mScheduler = null; private boolean mIsConnectedToXBMC; private RequestQueue mRequestQueue; private boolean showOnce = false; private Host mHost; private Connection() { mRequestQueue = getRequestQueue(); } public static synchronized Connection getInstance() { if (sConn == null) { sConn = new Connection(); } return sConn; } public Player getPlayer() { return this.mPlayer; } public void checkWiFi() { Context context = AndroidApplication.getInstance().getApplicationContext(); ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!networkInfo.isConnected()) { Toast.makeText(context, context.getString(R.string.WiFiDisabled), Toast.LENGTH_SHORT).show(); setIsConnectedToXBMC(false); } } private <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } private RequestQueue getRequestQueue() { if (mRequestQueue == null) { Context ctx = AndroidApplication.getInstance().getApplicationContext(); mRequestQueue = Volley.newRequestQueue(ctx.getApplicationContext()); } return mRequestQueue; } void initScheduler() { mPlayer = new Player(); stopScheduler(); sendToXBMC(new JSONRPCRequest(JSONRequestFactory.REQ_GET_VERSION)); mScheduler = Executors.newScheduledThreadPool(1); final JSONRPCRequest req1 = new JSONRPCRequest(JSONRequestFactory.REQ_ACTIVE_PLAYERS); final JSONRPCRequest req2 = new JSONRPCRequest(JSONRequestFactory.REQ_GET_PROPERTIES); final JSONRPCRequest req3 = new JSONRPCRequest(JSONRequestFactory.REQ_GET_ITEMS); final JSONRPCRequest req4 = new JSONRPCRequest(JSONRequestFactory.REQ_GET_ITEM); Runnable pinger = new Runnable() { public void run() { // Log.v(TAG, "Ping!"); sendToXBMC(req1); sendToXBMC(req2); sendToXBMC(req3); if (mPlayer.getType().equals(sVideoPlayer)) { sendToXBMC(req4); } } }; mScheduler.scheduleAtFixedRate(pinger, 0, 2, TimeUnit.SECONDS); } public void initConnectionXBMC(ProviderService gearService) { this.mgearService = gearService; Log.v(TAG, "Init connection"); initScheduler(); } public static HttpURLConnection getURLConnection(Host h) throws IOException { String uri = "http://" + h.getIp() + ":" + h.getPort() + XBMC_JSONRPC_BOOTSTRAP; URL url = new URL(uri); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setReadTimeout(5000); urlConn.setConnectTimeout(5000); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setRequestProperty("Accept", "application/json"); urlConn.setRequestProperty("Content-type", "application/json"); return urlConn; } public Host getCurrentActiveHost() { return mHost; } public void setHost(Host host) { if (host != null) { this.mHost = host; String ip; int port; ip = host.getIp(); port = host.getPort(); this.mBase64Auth = getBase64Auth(host.getUsername(), host.getPassword()); if (ip.isEmpty() || port <= 0) { mUrl = null; } else { mUrl = "http://" + ip + ":" + port + XBMC_JSONRPC_BOOTSTRAP; } } else { mUrl = null; this.mHost = null; } } public void sendWol() { if (mHost != null) { String _ip = mHost.getIp(); String mac = mHost.getHardware(); WakeOnLan wol = new WakeOnLan(mac, _ip); wol.run(); } } public void sendToXBMC(final JSONRPCRequest req) { req.replaceIDs(mPlayer); final Context ctx = AndroidApplication.getInstance().getApplicationContext(); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, mUrl, req.getRequest(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { req.setResponse(response); ResponseParser.parse(mPlayer, req); if (!mIsConnectedToXBMC) { setIsConnectedToXBMC(true); showOnce = true; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (showOnce) { Toast.makeText(ctx, ctx.getString(R.string.error), Toast.LENGTH_SHORT).show(); showOnce = false; } setIsConnectedToXBMC(false); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", mBase64Auth); return params; } }; addToRequestQueue(jsObjRequest); } private String getBase64Auth(String user, String password) { try { String _cred = user + ":" + password; byte[] data; data = _cred.getBytes("UTF-8"); return "Basic " + Base64.encodeToString(data, Base64.DEFAULT).trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public boolean isConnectedToGear() { if (mgearService == null) { mgearService = ProviderService.getInstance(); } return mgearService != null && mgearService.isConnected(); } private void stopScheduler() { if (mScheduler != null && !mScheduler.isShutdown()) { mScheduler.shutdown(); mScheduler = null; } } public void stopConnectionToXBMC() { stopScheduler(); getRequestQueue().cancelAll(new RequestQueue.RequestFilter() { @Override public boolean apply(Request<?> request) { return true; } }); mPlayer = null; setIsConnectedToXBMC(false); Log.v(TAG, "Stop connection"); } private void sendBroadcast(int value) { Intent intent = new Intent(MainActivity.INTENT_FILTER); intent.putExtra(MainActivity.INT_EXTRA, value); AndroidApplication.getInstance().getApplicationContext() .sendBroadcast(intent); } void setIsConnectedToXBMC(boolean isConnected) { String text = ""; if (!this.mIsConnectedToXBMC && isConnected) { sendBroadcast(MainActivity.CONNECTED_XBMC); text = GearJSON.CONNECTED_XBMC; } else if (!isConnected) { text = GearJSON.DISCONNECTED_XBMC; sendBroadcast(MainActivity.DISCONNECTED_XBMC); } if (mgearService != null) { mgearService.sendToGear(text); } this.mIsConnectedToXBMC = isConnected; } public boolean isConnectedToXBMC() { return mIsConnectedToXBMC; } }