-1

I created an app that send the location feeds to server in background , I need a button (control) to force stop the app or kill the background process. how can I implement it ?

do in background function is only used not the Service

public class SendRequest extends AsyncTask<String, Void, String> {
 protected String doInBackground(String... arg0) {

        try {
     URL url = new URL(GlobalVariables.URL_REGISTRATION_AND_UPDATION);
//convert string to jsonoblects
            JSONObject postDataParams = new JSONObject();

//add the strings needed to send("first part is for string name","second part for content")
             postDataParams.put(GlobalVariables.PARAM_LATTITUDE, latitude);
           postDataParams.put(GlobalVariables.PARAM_LONGITUDE, longitude);
}
}
Edwin Thomas
  • 87
  • 1
  • 13

2 Answers2

0

Cancel AsyncTask

You have a 'one line command' that performs a very long operation, there's not much you can do.

The best workaround would be to use your own cancelFlag boolean. You can then test this cancelFlag in your postExecute to decide what to do with the result.


To stop a background service call this method

mContext.stopService(new Intent(mContext, MyBackgroundService.class))

To stop the app you can use the finishAffinity method, which seems to be pretty close to closing all related activities by its name and javadoc description:

this.finishAffinity();

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.

Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.


If you really want to force stop your app, just like in the application info of the device use this, taken from here:

Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());    
os.writeBytes("adb shell" + "\n");    
os.flush();    
os.writeBytes("am force-stop com.YOUR.PACKAGENAME" + "\n");   
os.flush();
Community
  • 1
  • 1
Denny
  • 1,766
  • 3
  • 17
  • 37
0
android.os.Process.killProcess(android.os.Process.myPid());
Nick Wu
  • 3
  • 2
  • I need to foce stop my app. – Edwin Thomas May 19 '17 at 10:07
  • **From review queue:** May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – help-info.de May 19 '17 at 17:31