How do I stop the 'VpnService' service in java when I click on a button?












0















I'm looking for a way to change DNS on Android, so I found a tutorial showing how to create a VPN connection. Once implemented, I can initiate this VPN connection in my app at the click of a button, but I can not do the opposite: disable this connection by clicking another button. How can I do that?



Procedure calling the service:



public void vpn() {
Intent intent = android.net.VpnService.prepare(getApplicationContext());

if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, DNSVpnService.class);
startService(intent);
Toast.makeText(getBaseContext(), "OpenDNS Ativado", Toast.LENGTH_SHORT).show();
}
}


DNSVpnService class:



public class DNSVpnService extends android.net.VpnService {

private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();

// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("OpenDNS")
.addAddress("192.168.0.1", 24)
.addDnsServer("208.67.222.222")
//.addRoute("0.0.0.0", 0)
.establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
//e. Use a loop to pass packets.
while (true) {
//get packet with in
//put packet to tunnel
//get packet form tunnel
//return packet with out
//sleep is a must
Thread.sleep(100);
}

} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {

}
}
}

}, "OpenDNS");

//start the service
mThread.start();
return START_STICKY;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}


Sorry, but I'm very newbie and would like examples ...










share|improve this question

























  • Try this stackoverflow.com/questions/3165190/…

    – royatirek
    Nov 26 '18 at 11:44
















0















I'm looking for a way to change DNS on Android, so I found a tutorial showing how to create a VPN connection. Once implemented, I can initiate this VPN connection in my app at the click of a button, but I can not do the opposite: disable this connection by clicking another button. How can I do that?



Procedure calling the service:



public void vpn() {
Intent intent = android.net.VpnService.prepare(getApplicationContext());

if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, DNSVpnService.class);
startService(intent);
Toast.makeText(getBaseContext(), "OpenDNS Ativado", Toast.LENGTH_SHORT).show();
}
}


DNSVpnService class:



public class DNSVpnService extends android.net.VpnService {

private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();

// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("OpenDNS")
.addAddress("192.168.0.1", 24)
.addDnsServer("208.67.222.222")
//.addRoute("0.0.0.0", 0)
.establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
//e. Use a loop to pass packets.
while (true) {
//get packet with in
//put packet to tunnel
//get packet form tunnel
//return packet with out
//sleep is a must
Thread.sleep(100);
}

} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {

}
}
}

}, "OpenDNS");

//start the service
mThread.start();
return START_STICKY;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}


Sorry, but I'm very newbie and would like examples ...










share|improve this question

























  • Try this stackoverflow.com/questions/3165190/…

    – royatirek
    Nov 26 '18 at 11:44














0












0








0








I'm looking for a way to change DNS on Android, so I found a tutorial showing how to create a VPN connection. Once implemented, I can initiate this VPN connection in my app at the click of a button, but I can not do the opposite: disable this connection by clicking another button. How can I do that?



Procedure calling the service:



public void vpn() {
Intent intent = android.net.VpnService.prepare(getApplicationContext());

if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, DNSVpnService.class);
startService(intent);
Toast.makeText(getBaseContext(), "OpenDNS Ativado", Toast.LENGTH_SHORT).show();
}
}


DNSVpnService class:



public class DNSVpnService extends android.net.VpnService {

private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();

// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("OpenDNS")
.addAddress("192.168.0.1", 24)
.addDnsServer("208.67.222.222")
//.addRoute("0.0.0.0", 0)
.establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
//e. Use a loop to pass packets.
while (true) {
//get packet with in
//put packet to tunnel
//get packet form tunnel
//return packet with out
//sleep is a must
Thread.sleep(100);
}

} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {

}
}
}

}, "OpenDNS");

//start the service
mThread.start();
return START_STICKY;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}


Sorry, but I'm very newbie and would like examples ...










share|improve this question
















I'm looking for a way to change DNS on Android, so I found a tutorial showing how to create a VPN connection. Once implemented, I can initiate this VPN connection in my app at the click of a button, but I can not do the opposite: disable this connection by clicking another button. How can I do that?



Procedure calling the service:



public void vpn() {
Intent intent = android.net.VpnService.prepare(getApplicationContext());

if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, DNSVpnService.class);
startService(intent);
Toast.makeText(getBaseContext(), "OpenDNS Ativado", Toast.LENGTH_SHORT).show();
}
}


DNSVpnService class:



public class DNSVpnService extends android.net.VpnService {

private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();

// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("OpenDNS")
.addAddress("192.168.0.1", 24)
.addDnsServer("208.67.222.222")
//.addRoute("0.0.0.0", 0)
.establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
//e. Use a loop to pass packets.
while (true) {
//get packet with in
//put packet to tunnel
//get packet form tunnel
//return packet with out
//sleep is a must
Thread.sleep(100);
}

} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {

}
}
}

}, "OpenDNS");

//start the service
mThread.start();
return START_STICKY;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}


Sorry, but I'm very newbie and would like examples ...







java android service






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 17:12









Fantômas

32.5k156388




32.5k156388










asked Nov 25 '18 at 16:05









Wígny AlmeidaWígny Almeida

1




1













  • Try this stackoverflow.com/questions/3165190/…

    – royatirek
    Nov 26 '18 at 11:44



















  • Try this stackoverflow.com/questions/3165190/…

    – royatirek
    Nov 26 '18 at 11:44

















Try this stackoverflow.com/questions/3165190/…

– royatirek
Nov 26 '18 at 11:44





Try this stackoverflow.com/questions/3165190/…

– royatirek
Nov 26 '18 at 11:44












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469303%2fhow-do-i-stop-the-vpnservice-service-in-java-when-i-click-on-a-button%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469303%2fhow-do-i-stop-the-vpnservice-service-in-java-when-i-click-on-a-button%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)