1 /* 2 * Copyright (C) 2011 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 17 package com.example.android.toyvpn; 18 19 import android.app.Activity; 20 import android.content.Intent; 21 import android.content.SharedPreferences; 22 import android.net.VpnService; 23 import android.os.Bundle; 24 import android.widget.TextView; 25 26 public class ToyVpnClient extends Activity { 27 public interface Prefs { 28 String NAME = "connection"; 29 String SERVER_ADDRESS = "server.address"; 30 String SERVER_PORT = "server.port"; 31 String SHARED_SECRET = "shared.secret"; 32 } 33 34 @Override onCreate(Bundle savedInstanceState)35 public void onCreate(Bundle savedInstanceState) { 36 super.onCreate(savedInstanceState); 37 setContentView(R.layout.form); 38 39 final TextView serverAddress = (TextView) findViewById(R.id.address); 40 final TextView serverPort = (TextView) findViewById(R.id.port); 41 final TextView sharedSecret = (TextView) findViewById(R.id.secret); 42 43 final SharedPreferences prefs = getSharedPreferences(Prefs.NAME, MODE_PRIVATE); 44 serverAddress.setText(prefs.getString(Prefs.SERVER_ADDRESS, "")); 45 serverPort.setText(prefs.getString(Prefs.SERVER_PORT, "")); 46 sharedSecret.setText(prefs.getString(Prefs.SHARED_SECRET, "")); 47 48 findViewById(R.id.connect).setOnClickListener(v -> { 49 prefs.edit() 50 .putString(Prefs.SERVER_ADDRESS, serverAddress.getText().toString()) 51 .putString(Prefs.SERVER_PORT, serverPort.getText().toString()) 52 .putString(Prefs.SHARED_SECRET, sharedSecret.getText().toString()) 53 .commit(); 54 55 Intent intent = VpnService.prepare(ToyVpnClient.this); 56 if (intent != null) { 57 startActivityForResult(intent, 0); 58 } else { 59 onActivityResult(0, RESULT_OK, null); 60 } 61 }); 62 findViewById(R.id.disconnect).setOnClickListener(v -> { 63 startService(getServiceIntent().setAction(ToyVpnService.ACTION_DISCONNECT)); 64 }); 65 } 66 67 @Override onActivityResult(int request, int result, Intent data)68 protected void onActivityResult(int request, int result, Intent data) { 69 if (result == RESULT_OK) { 70 startService(getServiceIntent().setAction(ToyVpnService.ACTION_CONNECT)); 71 } 72 } 73 getServiceIntent()74 private Intent getServiceIntent() { 75 return new Intent(this, ToyVpnService.class); 76 } 77 } 78