1 /*
2  * Copyright (C) 2017 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.android.cts.vpnfirewall;
18 
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.net.VpnService;
22 import android.os.Bundle;
23 
24 public class VpnClient extends Activity {
25 
26     public static final String ACTION_CONNECT_AND_FINISH =
27             "com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH";
28     public static final String ACTION_DISCONNECT_AND_FINISH =
29             "com.android.cts.vpnfirewall.action.DISCONNECT_AND_FINISH";
30 
31     private static final int REQUEST_CONNECT = 0;
32     private static final int REQUEST_CONNECT_AND_FINISH = 1;
33 
34     @Override
onCreate(Bundle savedInstanceState)35     public void onCreate(Bundle savedInstanceState) {
36         super.onCreate(savedInstanceState);
37         setContentView(R.layout.vpn_client);
38 
39         if (ACTION_CONNECT_AND_FINISH.equals(getIntent().getAction())) {
40             prepareAndStart(REQUEST_CONNECT_AND_FINISH);
41         }
42         if (ACTION_DISCONNECT_AND_FINISH.equals(getIntent().getAction())) {
43             // the easiest way to stop the VpnService is to to start it with a stop action
44             Intent stopServiceIntent = new Intent(this, ReflectorVpnService.class)
45                     .setAction(ReflectorVpnService.ACTION_STOP_SERVICE);
46             startService(stopServiceIntent);
47             finish();
48         }
49         findViewById(R.id.connect).setOnClickListener(v -> prepareAndStart(REQUEST_CONNECT));
50     }
51 
52     @Override
onActivityResult(int request, int result, Intent data)53     protected void onActivityResult(int request, int result, Intent data) {
54         if (result == RESULT_OK) {
55             startService(new Intent(this, ReflectorVpnService.class));
56         }
57         if (request == REQUEST_CONNECT_AND_FINISH) {
58             finish();
59         }
60     }
61 
prepareAndStart(int requestCode)62     private void prepareAndStart(int requestCode) {
63         Intent intent = VpnService.prepare(VpnClient.this);
64         if (intent != null) {
65             startActivityForResult(intent, requestCode);
66         } else {
67             onActivityResult(requestCode, RESULT_OK, null);
68         }
69     }
70 }
71