Android Open Source - Android-Apps Connection






From Project

Back to project page Android-Apps.

License

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.

Java Source Code

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;
    }
}




Java Source Code List

com.kniezrec.remoterecorder.Communication.java
com.kniezrec.remoterecorder.MainServiceConnection.java
com.kniezrec.remoterecorder.MainService.java
com.kniezrec.remoterecorder.RequestType.java
com.kniezrec.remoterecorder.Request.java
com.kniezrec.voiceremote2.BSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremote2.BSeriesSender.java
com.kniezrec.voiceremote2.CSeriesButtons.java
com.kniezrec.voiceremote2.CSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremote2.CSeriesSender.java
com.kniezrec.voiceremote2.CommandsFragment.java
com.kniezrec.voiceremote2.Commands.java
com.kniezrec.voiceremote2.Discovery.java
com.kniezrec.voiceremote2.FSeriesButtons.java
com.kniezrec.voiceremote2.Group.java
com.kniezrec.voiceremote2.HelpFragment.java
com.kniezrec.voiceremote2.HostnamePreference.java
com.kniezrec.voiceremote2.KeyCodeSender.java
com.kniezrec.voiceremote2.ListActionsFragment.java
com.kniezrec.voiceremote2.MainActivity.java
com.kniezrec.voiceremote2.MainFragment.java
com.kniezrec.voiceremote2.Mapper.java
com.kniezrec.voiceremote2.MyExpandableListAdapter.java
com.kniezrec.voiceremote2.NewActionEdit.java
com.kniezrec.voiceremote2.NewActionSingleEdit.java
com.kniezrec.voiceremote2.NewAction.java
com.kniezrec.voiceremote2.RemoteButton.java
com.kniezrec.voiceremote2.SenderFactory.java
com.kniezrec.voiceremote2.Sender.java
com.kniezrec.voiceremote2.SettingsActivity.java
com.kniezrec.voiceremote2.TextSender.java
com.kniezrec.voiceremotefree.BSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremotefree.BSeriesSender.java
com.kniezrec.voiceremotefree.CSeriesButtons.java
com.kniezrec.voiceremotefree.CSeriesKeyCodeSenderFactory.java
com.kniezrec.voiceremotefree.CSeriesSender.java
com.kniezrec.voiceremotefree.Commands.java
com.kniezrec.voiceremotefree.Discovery.java
com.kniezrec.voiceremotefree.FSeriesButtons.java
com.kniezrec.voiceremotefree.HelpActivity.java
com.kniezrec.voiceremotefree.HostnamePreference.java
com.kniezrec.voiceremotefree.KeyCodeSender.java
com.kniezrec.voiceremotefree.ListActionsActivity.java
com.kniezrec.voiceremotefree.MainActivity.java
com.kniezrec.voiceremotefree.Mapper.java
com.kniezrec.voiceremotefree.NewActionEdit.java
com.kniezrec.voiceremotefree.NewActionSingleEdit.java
com.kniezrec.voiceremotefree.NewAction.java
com.kniezrec.voiceremotefree.RemoteButton.java
com.kniezrec.voiceremotefree.SenderFactory.java
com.kniezrec.voiceremotefree.Sender.java
com.kniezrec.voiceremotefree.Setings.java
com.kniezrec.voiceremotefree.SettingsActivity.java
com.kniezrec.voiceremotefree.TextSender.java
com.kniezrec.xbmcgear.connection.AndroidApplication.java
com.kniezrec.xbmcgear.connection.Connection.java
com.kniezrec.xbmcgear.connection.GearJSON.java
com.kniezrec.xbmcgear.connection.JSONRPCRequest.java
com.kniezrec.xbmcgear.connection.JSONRequestFactory.java
com.kniezrec.xbmcgear.connection.NSDResolve.java
com.kniezrec.xbmcgear.connection.NSDSearch.java
com.kniezrec.xbmcgear.connection.ProviderConnection.java
com.kniezrec.xbmcgear.connection.ProviderService.java
com.kniezrec.xbmcgear.connection.ResponseParser.java
com.kniezrec.xbmcgear.connection.WakeOnLan.java
com.kniezrec.xbmcgear.player.Kodi.java
com.kniezrec.xbmcgear.player.Player.java
com.kniezrec.xbmcgear.player.Playlist.java
com.kniezrec.xbmcgear.player.Song.java
com.kniezrec.xbmcgear.player.Video.java
com.kniezrec.xbmcgear.preferences.HostTable.java
com.kniezrec.xbmcgear.preferences.Host.java
com.kniezrec.xbmcgear.preferences.HostsDataSource.java
com.kniezrec.xbmcgear.preferences.HostsDatabaseHelper.java
com.kniezrec.xbmcgear.preferences.SharedPreferencesUtil.java
com.kniezrec.xbmcgear.presentation.AnimationManager.java
com.kniezrec.xbmcgear.presentation.AutoConfigurationActivity.java
com.kniezrec.xbmcgear.presentation.HostSetActivity.java
com.kniezrec.xbmcgear.presentation.InstanceActivity.java
com.kniezrec.xbmcgear.presentation.MainActivity.java
com.kniezrec.xbmcgear.presentation.StyleDialogFragment.java
com.kniezrec.xbmcgear.presentation.ViewMode.java
com.uraroji.garage.android.lame.SimpleLame.java
com.uraroji.garage.android.mp3recvoice.RecMicToMp3.java
de.quist.samy.remocon.Base64.java
de.quist.samy.remocon.Base64.java
de.quist.samy.remocon.ConnectionDeniedException.java
de.quist.samy.remocon.ConnectionDeniedException.java
de.quist.samy.remocon.Key.java
de.quist.samy.remocon.Key.java
de.quist.samy.remocon.Loggable.java
de.quist.samy.remocon.Loggable.java
de.quist.samy.remocon.RemoteReader.java
de.quist.samy.remocon.RemoteReader.java
de.quist.samy.remocon.RemoteSession.java
de.quist.samy.remocon.RemoteSession.java