background and run continuous without close - java

I make mobile lost gps tracking application, that code will be running in only activity..
my application strategy is.
1) if found http://192.168.43.164/imei_000000000000000.txt file then find
"track" or "find_mobile" string in imei_000000000000000.txt.
2) if "track" or "find_mobile" string is found in imei_000000000000000.txt file then post
"http://192.168.43.164/add.php?long_itude=22.00023&lat_itude=22.00023." link
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<String> urls = new ArrayList<String>();
try{
URL url = new URL("http://192.168.43.164/imei_000000000000000.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
while ((str = in.readLine()) != null)
{
urls.add(str);
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
li = urls.get(0);
if (li.equals("track") || li.equals("find_mobile")) {
try{
URL url = new URL("http://192.168.43.164/add.php?long_itude=22.00023&lat_itude=22.00023");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
while ((str = in.readLine()) != null)
{
urls.add(str);
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "hello", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getBaseContext(), "not found"+ li, Toast.LENGTH_SHORT).show();
}
}
} );
}
}).start();
}
},5,5, TimeUnit.SECONDS);
posted code will work fine, but it's code working only in activity.
I want make that code background and run continuous without close.

use new thread = (Thread) function

Related

Cannot show the Toast through the Callback function

Here is the httpPost to send the data to server and get the response.
public void httpPost(String URL ) {
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
stringBuilder.setLength(0);
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
callback.success(stringBuilder.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Here is the Callback function to setup the string from server response.
public interface Callback{
void success(String string);
}
Click the button and post the data to server. Here can get the response of the string from Callback function but it cannot show the toast.
button.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
server.httpPost("https://google.com/index.php?username=Peter");
server.callback =new Server.Callback() {
#Override
public void success(String response) {
Log.d("test",response);
Toast.makeText(AddActivity.this, response,Toast.LENGTH_SHORT).show();
}
};
}
});
You must run the Toast on UI thread using the following code:
<Activity>.runOnUiThread(new Runnable() {
#Override
public void run() {
(Toast and other UI changes here...)
}
});

Display a toast in Async

So I am trying to display a toast if the link that provided in "EditText" is equal to a specific link.
Else the code keep runing until result.
Thats how I tried to do(Its not detecting the link):
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","Error!");
}
My main code,if you need anything else from the code just tell me and I will upload:
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(final String... urls) {
Log.e("URL", "Loading url = " + urls[0]);
StringBuilder result = new StringBuilder();
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","DSADSADASDASDAS");
}
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
} catch (MalformedURLException e) {
result.append("Error: MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#SuppressLint("SetTextI18n")
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.e("JSON data",""+weatherInfo);
Toast.makeText(MainActivity.this, mCityName +" has been loaded", Toast.LENGTH_SHORT).show();
JSONArray jArray = new JSONArray(weatherInfo);
for(int i = 0; 0 < jArray.length(); i++){
JSONObject partJson = jArray.getJSONObject(i);
mMain.setText("The Weather in " + mCityName + " is: " + partJson.getString("main"));
mDescription.setText("And " + partJson.getString("description"));
mMain.setVisibility(View.VISIBLE);
mDescription.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you !
To show a Toast from a background thread you need to call it inside runOnUIThread like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "URL is the same", Toast.LENGTH_SHORT).show();
}
});
This is assuming your AsincTask is inside an activity class.
runOnUIThread is a method of Activity class, and you need a Context to show the Toast.
If your AsyncTask is in a separate class, you will need to provide an Activity as a parameter, or use an Intent to communicate with an Activity.

How can I delay a funtion call? [duplicate]

This question already has answers here:
How to call a method after a delay in Android
(35 answers)
Closed 4 years ago.
public class NotificationReceivedCheckDelivery extends NotificationExtenderService {
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
OverrideSettings overrideSettings = new OverrideSettings();
overrideSettings.extender = new NotificationCompat.Extender() {
#Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
// Sets the background notification color to Yellow on Android 5.0+ devices.
return builder.setColor(new BigInteger("FFFFEC4F", 16).intValue());
}
};
OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
Log.d("ONES",receivedResult.payload.title);
JSONObject AdditionalData = receivedResult.payload.additionalData;
Log.d("Adata",AdditionalData.toString());
String uuid= null;
try{
// {"uuid":"adddd"}
uuid = AdditionalData.getString("uuid");
}
catch (JSONException e){
Log.e("Error JSON","UUID",e);
}
// Create Object and call AsyncTask execute Method
new FetchNotificationData().execute(uuid);
return true;
}
private class FetchNotificationData extends AsyncTask<String,Void, String> {
#Override
protected String doInBackground(String... uuids) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
URL url = new URL("http://test.com/AppDeliveryReport?uuid="+uuids[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
return forecastJsonStr;
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("json", s);
}
}
}
I want to delay calling the FetchNotificationData function with a random seconds.
This is a delivery report url request function. Whenever a notification from onesignal received at the app it will call the url. I don't want to blast the server with huge request at once. So I want to delay call with random seconds so that server will have to serve few calls on a given time.
You can use handler to delay call to function
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(Splash.this, "I will be called after 2 sec",
Toast.LENGTH_SHORT).show();
//Call your Function here..
}
}, 2000); // 2000 = 2 sec
you can use Handler like this
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// your FetchNotificationData function
}
},timeInMiliSec);
just remember to import Handler as android.os, not java.util.logging
timer = new Timer();
final int FPS = 3;
TimerTask updateBall = new UpdateBallTask();
timer.scheduleAtFixedRate(updateBall, 0, 1000 * FPS);
class:
class UpdateBallTask extends TimerTask {
public void run() {
// do work
}
}
///OR
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
handler.postDelayed(this, 100);
// do work
handler.removeCallbacksAndMessages(null);
}
};
handler.postDelayed(r, 100);

How to start an Activity from AsyncTask?

I've build an AsyncTask and want to start another Activity when it ends (onPostExecute) but it won't work and I can't find the problem. Maybe there is a problem with String, String, String ?
Here is my code:
public class StartSearch extends AsyncTask<String, String, String> {
private Activity activity;
#Override
protected String doInBackground(String... strings) {
StringBuilder sb = new StringBuilder();
String http = "https://list-creater-service.herokuapp.com/api/v1/search";
HttpURLConnection urlConnection = null;
JSONObject json = null;
HttpResponse response = null;
try {
//connect to server
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("gamemode", gametype);
jsonParam.put("country", selCountry);
jsonParam.put("min_size", minSize);
jsonParam.put("max_size", maxSize);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String jsonS = sb.toString();
JSONArray jsonArray = new JSONArray(jsonS);
int length = jsonArray.length();
String[] names = new String[length];
for (int i = 0; i < length; i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
ArrayList serverList = new ArrayList();
serverList.add(jsonObject.getString("name"));
serverData = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = serverData.edit();
Set<String> set = new HashSet<String>();
set.addAll(serverList);
editor.putStringSet("name", set);
editor.commit();
System.out.println(jsonObject.getString("name"));
names[i] = jsonObject.getString("name");
}
//String name = jsonObject.getString("name");
System.out.println("" + sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
activity.startActivity(new Intent(activity, ServerIndex.class));
}
}
Need some help!
Thx :)
You have Activity activity declared , but you have not assigned your current activity context to it . Assign the current activity context to it.
Like
activity=currentContext;
You should use runOnUIThread in your onPostExecute
runOnUiThread(new Runnable() {
public void run() {
activity.startActivity(new Intent(activity, ServerIndex.class));
}});
And as Raghunandan said, activity is not initialized. You can access the startActivity method from your StartSearch class by using
SomeActivity.this.startActivity (SomeActivity has to be initialized)
And since onPostExecute runs on the UI thread, you may or may not call runOnUIThread.

How to stop HttpURLConnection.getInputStream()?

Below is my code:
private HttpURLConnection connection;
private InputStream is;
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
is = connection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopupload() {
connection = null;
is = null;
}
When I upload file, the line is = connection.getInputStream(); will spend a lot of time to get reply. So I want to implement a stop function as stopupload(). But if I call stopupload() while the code is handling at line is = connection.getInputStream();, it still needs to wait for its reply.
I want to stop waiting at once while implement stopupload(). How can I do it?
But if I call stopupload() while the code is handling at line is =
connection.getInputStream();, it still needs to wait for its reply.
Starting from HoneyComb, all network operations are not allowed to be executed over main thread. To avoid getting NetworkOnMainThreadException, you may use Thread or AsyncTask.
I want to stop waiting at once while implement stopupload(). How can I
do it?
Below code gives the user to stop uploading after 2 seconds, but you can modify the sleep times (should be less than 5 seconds) accordingly.
upload:
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
// run uploading activity within a Thread
Thread t = new Thread() {
public void run() {
is = connection.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
}
// sleep 2 seconds before "stop uploading" button appears
mHandler.postDelayed(new Runnable() {
public void run() {
mBtnStop.setVisibility(View.VISIBLE);
}
}, 2000);
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (connection != null) {
connection.disconnect();
}
}
}
onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
// more codes...
Handler mHandler = new Handler();
mBtnStop = (Button) findViewById(R.id.btn_stop);
mBtnStop.setBackgroundResource(R.drawable.stop_upload);
mBtnStop.setOnClickListener(mHandlerStop);
mBtnStop.setVisibility(View.INVISIBLE);
View.OnClickListener mHandlerStop = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopUpload(); // called when "stop upload" button is clicked
}
};
// more codes...
}
private HttpURLConnection connection;
private InputStream is;
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Thread t = new Thread() {
public void run() {
is = connection.getInputStream();
}
};
t.start()
} catch (Exception e) {
e.printStackTrace();
}catch (InterruptedException e) {
stopupload(connection ,is, t);
}
}
public void stopupload(HttpURLConnection connection ,InputStream is,Thread t) {
if(connection != null ){
try {
t.interupt();
running = false;
connection=null;
is=null;
} catch (Exception e) {
}
}
}
Wrap the code that uses HttpURLConnection inside a Future, as described here.

Categories