I'm trying to send a request to the local server in the background. But I fail.
class MyService2 : Service() {
..........
fun Check_Presence(){
var url="http://192.168.1.158/cgi-bin/cp/login.sh"
val queue = Volley.newRequestQueue(this)
val postRequest = object : StringRequest(
Request.Method.POST, url,
Response.Listener {response ->
Toast.makeText(getBaseContext(), "response"+response, Toast.LENGTH_LONG).show();
},
Response.ErrorListener() { response ->
Toast.makeText(getBaseContext(), "Not Send Request", Toast.LENGTH_LONG).show();
}
) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["status"] = "1"
return params
}
}
queue.add(postRequest)
}
}
manifest file :
<application
........
<service
android:name=".MyService2"
android:enabled="true"
android:exported="true">
</service>
</application>
MainActivity :
val serviceClass = MyService2::class.java
val serviceIntent = Intent(this, serviceClass)
this.startService(serviceIntent)
As long as the program is running, it works correctly and displays the response ... message.
But when I close the program, the program displays the "Not Send Request" message.
Note:The Check_Presence function runs every minute.
When I checked the Internet at the service, I realized that the internet was not connected.
fun Check_Internet(){
val connectivityManager=this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo=connectivityManager.activeNetworkInfo
if (networkInfo!=null && networkInfo.isConnected) {
Toast.makeText(applicationContext, "INTENET OK : ", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(applicationContext, "NO INTERNET : ", Toast.LENGTH_LONG).show();
}
}
Please help me.
My device : Android 8
If you don't mind I would ask you to check or perform 3 things-
Have you taken Internet and Network Access permission in your manifest?
Please use Retrofit library for HTTP purposes as Retrofit is a highly maintained, easy and efficient library
Before you call your localhost server (or whatsoever) test it with Postman app to get a clear view of your network status, server performance etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.