Android Open Source - Android-Apps Main Service






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.remoterecorder;
/* w  w  w.  j  a va2s  .  c  om*/
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;

import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.accessory.SA;
import com.samsung.android.sdk.accessory.SAAgent;
import com.samsung.android.sdk.accessory.SAAuthenticationToken;
import com.samsung.android.sdk.accessory.SAPeerAgent;
import com.samsung.android.sdk.accessory.SASocket;
import com.samsung.android.sdk.accessoryfiletransfer.SAFileTransfer;
import com.samsung.android.sdk.accessoryfiletransfer.SAFileTransfer.EventListener;
import com.samsung.android.sdk.accessoryfiletransfer.SAft;
import com.uraroji.garage.android.mp3recvoice.RecMicToMp3;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import javax.security.cert.X509Certificate;

public class MainService extends SAAgent {
    public static final String DIR_NAME = "/RemoteRecorder/";
    private static final String TAG = "MainServiceRemote";
    private static boolean sIsRecordingFlag = false;
    private final IBinder mBinder = new LocalBinder();
    private final String DURATION_PREF = "duration_preference";
    private String mResponse;
    private RecMicToMp3 mRecMicToMp3 = null;
    private MainServiceConnection mConnection = null;
    private SAPeerAgent mPeerAgent;
    private SAFileTransfer mFileTransfer;
    private Timer mTimer;
    private int mTransactionID = -1;
    private LinkedHashMap<String, String> mFiles;
    private File mParentDir;
    private int mTimeMaxDuration;

    // private int authCount = 1;

    public MainService() {
        super(TAG, MainServiceConnection.class);
    }

    private static byte[] getApplicationCertificate(Context context) {
        if (context == null) {
            return null;
        }
        Signature[] sigs;
        byte[] certificat = null;
        String packageName = context.getPackageName();
        if (context != null) {
            try {
                PackageInfo pkgInfo = null;
                pkgInfo = context.getPackageManager().getPackageInfo(
                        packageName, PackageManager.GET_SIGNATURES);
                if (pkgInfo == null) {
                    return null;
                }
                sigs = pkgInfo.signatures;
                if (sigs == null) {
                } else {
                    CertificateFactory cf = CertificateFactory
                            .getInstance("X.509");
                    ByteArrayInputStream stream = new ByteArrayInputStream(
                            sigs[0].toByteArray());
                    X509Certificate cert;
                    cert = X509Certificate.getInstance(stream);
                    certificat = cert.getPublicKey().getEncoded();
                }
            } catch (NameNotFoundException e) {
                Log.v(TAG, e.getMessage());
            } catch (CertificateException e) {
                Log.v(TAG, e.getMessage());
            } catch (javax.security.cert.CertificateException e) {
                Log.v(TAG, e.getMessage());
            }

        }
        return certificat;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "onCreate of smart view Provider Service");
        SA mAccessory = new SA();
        try {
            mAccessory.initialize(this);
        } catch (SsdkUnsupportedException e) {
            // Error Handling
        } catch (Exception e1) {
            Log.e(TAG, "Cannot initialize Accessory package.");
            e1.printStackTrace();
            stopSelf();
        }
    }

    private LinkedHashMap<String, String> getFileList() {
        LinkedHashMap<String, String> list = new LinkedHashMap<>();
        mParentDir = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + MainService.DIR_NAME);
        if (!mParentDir.exists()) {
            try {
                mParentDir.mkdir();
            } catch (SecurityException e) {
                Log.v(TAG, e.getMessage());
            }
        }
        File[] files = mParentDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mp3");
            }
        });
        if (files != null) {
            for (File file : files) {
                list.put(file.getName(), file.getAbsolutePath());
            }
        }
        return list;
    }

    @Override
    protected void onServiceConnectionRequested(SAPeerAgent peerAgent) {
        Log.e(TAG, "acceptServiceConnectionRequest");
        acceptServiceConnectionRequest(peerAgent);
    }

    protected void onAuthenticationResponse(SAPeerAgent uPeerAgent,
                                            SAAuthenticationToken authToken, int error) {

        if (authToken.getAuthenticationType() == SAAuthenticationToken.AUTHENTICATION_TYPE_CERTIFICATE_X509) {
            Context mContext = getApplicationContext();
            byte[] myAppKey = getApplicationCertificate(mContext);

            if (authToken.getKey() != null) {
                boolean matched = true;
                if (authToken.getKey().length != myAppKey.length) {
                    matched = false;
                } else {
                    for (int i = 0; i < authToken.getKey().length; i++) {
                        if (authToken.getKey()[i] != myAppKey[i]) {
                            matched = false;
                        }
                    }
                }
                if (matched) {
                    acceptServiceConnectionRequest(uPeerAgent);
                }
            }
        } else if (authToken.getAuthenticationType() == SAAuthenticationToken.AUTHENTICATION_TYPE_NONE)
            Log.e(TAG, "onAuthenticationResponse : CERT_TYPE(NONE)");
    }

    @Override
    protected void onFindPeerAgentResponse(SAPeerAgent arg0, int arg1) {
        Log.d(TAG, "onFindPeerAgentResponse  arg1 =" + arg1);
    }

    private int getMaxDuration() {
        Context ctx = getApplicationContext();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(ctx);
        return prefs.getInt(DURATION_PREF, 5 * 60);
    }

    public void setMaxDuration(int duration) {
        Context ctx = getApplicationContext();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor edit = prefs.edit();
        edit.putInt(DURATION_PREF, duration);
        edit.apply();
        mTimeMaxDuration = duration;
        mRecMicToMp3.setMaxDuration(mTimeMaxDuration);
    }

    @Override
    protected void onServiceConnectionResponse(SASocket thisConnection,
                                               int result) {
        if (result == CONNECTION_SUCCESS) {

            if (thisConnection != null) {
                mFiles = getFileList();
                this.mConnection = (MainServiceConnection) thisConnection;
                this.mConnection.setMainService(this);
                if (mRecMicToMp3 == null) {
                    mRecMicToMp3 = new RecMicToMp3(8000);
                }
                mTimeMaxDuration = getMaxDuration();
                mRecMicToMp3.setMaxDuration(mTimeMaxDuration);
                mPeerAgent = thisConnection.getConnectedPeerAgent();

                mRecMicToMp3.setHandle(new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case RecMicToMp3.MSG_REC_STARTED:
                                mResponse = Request.MSG_REC_STARTED;
                                break;
                            case RecMicToMp3.MSG_REC_STOPPED:
                                mResponse = Request.MSG_REC_STOPPED;
                                break;
                            case RecMicToMp3.MSG_ERROR_GET_MIN_BUFFERSIZE:
                                mResponse = Request.MSG_ERROR_GET_MIN_BUFFERSIZE;
                                break;
                            case RecMicToMp3.MSG_ERROR_CREATE_FILE:
                                mResponse = Request.MSG_ERROR_CREATE_FILE;
                                break;
                            case RecMicToMp3.MSG_ERROR_REC_START:
                                mResponse = Request.MSG_ERROR_REC_START;
                                break;
                            case RecMicToMp3.MSG_ERROR_AUDIO_RECORD:
                                mResponse = Request.MSG_ERROR_AUDIO_RECORD;
                                break;
                            case RecMicToMp3.MSG_ERROR_AUDIO_ENCODE:
                                mResponse = Request.MSG_ERROR_AUDIO_ENCODE;
                                break;
                            case RecMicToMp3.MSG_ERROR_WRITE_FILE:
                                mResponse = Request.MSG_ERROR_WRITE_FILE;
                                break;
                            case RecMicToMp3.MSG_ERROR_CLOSE_FILE:
                                mResponse = Request.MSG_ERROR_CLOSE_FILE;
                                break;
                            default:
                                break;
                        }
                        mConnection.sendToGear(mResponse);
                    }
                });
                Log.e(TAG, "Connection Success");
            } else {
                Log.e(TAG, "SASocket object is null");
            }
        } else if (result == CONNECTION_ALREADY_EXIST) {
            if (thisConnection != null) {
                this.mConnection.sendToGear(Request.MSG_CONNECTION_EXISTS);
            }
        } else {
            Log.e(TAG, "onServiceConnectionResponse result error =" + result);
        }
    }

    boolean isRecording() {
        return mRecMicToMp3.isRecording();
    }

    void registerForFileTransfer() {
        SAft accessoryfiletransfer = new SAft();
        try {
            accessoryfiletransfer.initialize(this);
        } catch (SsdkUnsupportedException e) {
            e.printStackTrace();
        }
        EventListener mCallback = new EventListener() {
            @Override
            public void onProgressChanged(int transId, int progress) {
                Log.d(TAG, "progress received : " + progress
                        + " for transaction : " + transId);
            }

            @Override
            public void onTransferCompleted(int transId, String fileName,
                                            int errorCode) {
                Log.d(TAG, "transfer completed for transaction id : " + transId);
                Log.d(TAG, "file name : " + fileName);
                Log.d(TAG, "error code : " + errorCode);
                mFileTransfer = null;
                mTransactionID = transId;
            }

            @Override
            public void onTransferRequested(int transId, String fileName) {
                mTransactionID = transId;
            }
        };
        mFileTransfer = new SAFileTransfer(MainService.this, mCallback);
    }

    public void sendFile(String fileName) {
        String filePath = mFiles.get(fileName);
        if (filePath != null) {
            Log.e(TAG, "Send: " + filePath);
            if (mFileTransfer == null)
                registerForFileTransfer();
            try {
                mFileTransfer.send(mPeerAgent, filePath);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Send method failed:" + e.getMessage());
            }
        } else {
            mConnection.sendToGear(Request.FILE_DEL);
        }
    }

    void cancelFile() {
        if (mFileTransfer != null && mTransactionID != -1) {
            try {
                mFileTransfer.cancel(mTransactionID);
            } catch (IllegalArgumentException e) {
                mTransactionID = -1;
                Log.e(TAG, e.getMessage());
            }
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    void startRec() {
        if (!sIsRecordingFlag) {
            if (mRecMicToMp3 != null) {
                mTimer = new Timer();
                mTimer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        if (MainService.this.mConnection != null) {
                            MainService.this.mConnection.sendToGear(Request.SEC);
                        }
                        if (mRecMicToMp3.addSec()) {
                            stopRec();
                            MainService.this.mConnection.sendToGear(Request.MSG_REC_OVERTIME);
                        }
                    }
                }, 1000, 1000);
                mRecMicToMp3.start();
                sIsRecordingFlag = true;
            }
        }
    }

    String prepareJsonRequest(RequestType type) throws JSONException {
        JSONObject json = new JSONObject();
        switch (type) {
            case Single:
                json.put("type", "single");
                json.put("body", mRecMicToMp3.getmFileName());
                break;
            case Array:
                JSONArray list = new JSONArray();
                Set<String> _files = mFiles.keySet();
                for (String file : _files) {
                    list.put(file);
                }
                json.put("type", "array");
                json.put("body", list);
                json.put("maxDuration", mTimeMaxDuration);
                break;
        }

        return json.toString();
    }

    int gerCurrentTime() {
        return mRecMicToMp3.getSec();
    }

    void stopRec() {
        if (mRecMicToMp3 != null) {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            mRecMicToMp3.stop();
            sIsRecordingFlag = false;
            String path = mParentDir.getAbsolutePath() + "/" + mRecMicToMp3.getmFileName();
            mFiles.put(mRecMicToMp3.getmFileName(), path);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mConnection.close();
        stopRec();
    }

    public String deleteRecordFile(String... names) throws JSONException {
        JSONArray files = new JSONArray();
        if (names != null) {
            for (String name : names) {
                String absolutePath = mFiles.get(name);
                if (absolutePath != null) {
                    File file = new File(absolutePath);
                    if (file != null && file.delete()) {
                        mFiles.remove(name);
                        files.put(name);
                    }
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("type", "io");
        json.put("deletedFiles", files);
        return json.toString();
    }

    private class LocalBinder extends Binder {
        public MainService getService() {
            return MainService.this;
        }
    }
}




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