1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.rpc_performance; 18 19import android.app.Service; 20import android.content.Intent; 21import android.os.Binder; 22import android.os.Debug; 23import android.os.IBinder; 24import android.util.Log; 25import android.net.LocalServerSocket; 26import android.net.LocalSocket; 27 28import java.io.IOException; 29import java.io.InputStream; 30import java.io.OutputStream; 31 32public class MiscService extends Service { 33 34 public static final String SOCKET_NAME = "play-misc-service"; 35 private static final String TAG = "MiscService"; 36 37 private LocalServerSocket mServerSocket = null; 38 39 @Override public void onCreate() { 40 Log.v(TAG, "onCreate"); 41 try { 42 mServerSocket = new LocalServerSocket(SOCKET_NAME); 43 } catch (IOException e) { 44 Log.v(TAG, "in onCreate, making server socket: " + e); 45 return; 46 } 47 48 Thread t = new Thread() { 49 @Override public void run() { 50 LocalSocket socket = null; 51 while (true) { 52 try { 53 Log.v(TAG, "Waiting for connection..."); 54 socket = mServerSocket.accept(); 55 Log.v(TAG, "Got socket: " + socket); 56 if (socket != null) { 57 startEchoThread(socket); 58 } else { 59 return; // socket shutdown? 60 } 61 } catch (IOException e) { 62 Log.v(TAG, "in accept: " + e); 63 } 64 } 65 } 66 }; 67 t.start(); 68 } 69 70 private void startEchoThread(final LocalSocket socket) { 71 Thread t = new Thread() { 72 @Override public void run() { 73 try { 74 InputStream is = socket.getInputStream(); 75 OutputStream os = socket.getOutputStream(); 76 while (true) { 77 int byteRead = is.read(); 78 if (byteRead < 0) { 79 return; // EOF. 80 } 81 os.write(byteRead); 82 } 83 } catch (IOException e) { 84 Log.v(TAG, "in echo thread loop: " + e); 85 } 86 } 87 }; 88 t.start(); 89 } 90 91 @Override public IBinder onBind(Intent intent) { 92 Log.v(TAG, "onBind"); 93 return mBinder; 94 } 95 96 private final IService.Stub mBinder = new IService.Stub() { 97 public String pingString(String v) { 98 return v; 99 } 100 public void pingVoid() { 101 } 102 public void startTracing(String name) { 103 Debug.startMethodTracing(name); 104 } 105 public void stopTracing() { 106 Debug.stopMethodTracing(); 107 } 108 }; 109} 110