diff --git a/android-connectivity/app/build.gradle b/android-connectivity/app/build.gradle new file mode 100644 index 00000000..0afafcf6 --- /dev/null +++ b/android-connectivity/app/build.gradle @@ -0,0 +1,40 @@ +apply plugin: 'com.android.application' + +apply plugin: 'kotlin-android' + +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 28 + buildToolsVersion "29.0.2" + defaultConfig { + applicationId "com.hmkcode.connectivity" + minSdkVersion 19 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.core:core-ktx:1.1.0' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + // Coroutine + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2" + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha05" + + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' +} diff --git a/android-http/AndroidManifest.xml b/android-connectivity/app/src/main/AndroidManifest.xml similarity index 89% rename from android-http/AndroidManifest.xml rename to android-connectivity/app/src/main/AndroidManifest.xml index bcec53c5..16ef209d 100644 --- a/android-http/AndroidManifest.xml +++ b/android-connectivity/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@ + package="com.hmkcode.connectivity"> @@ -9,6 +9,7 @@ android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" + android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> diff --git a/android-connectivity/app/src/main/java/com/hmkcode/connectivity/MainActivity.kt b/android-connectivity/app/src/main/java/com/hmkcode/connectivity/MainActivity.kt new file mode 100644 index 00000000..a58dcc66 --- /dev/null +++ b/android-connectivity/app/src/main/java/com/hmkcode/connectivity/MainActivity.kt @@ -0,0 +1,74 @@ +package com.hmkcode.connectivity + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.os.Build +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.util.Log +import android.widget.TextView +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class MainActivity : AppCompatActivity() { + + lateinit var tvConnectivity: TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + tvConnectivity = findViewById(R.id.tvConnectivity) + + // get ConnectivityManager + val cm:ConnectivityManager = + getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + val builder: NetworkRequest.Builder = NetworkRequest.Builder() + cm.registerNetworkCallback( + + builder.build(), + object : ConnectivityManager.NetworkCallback() { + + override fun onAvailable(network: Network) { + lifecycleScope.launch { + Log.i("MainActivity", "onAvailable!") + + // check if NetworkCapabilities has TRANSPORT_WIFI + val isWifi:Boolean = cm.getNetworkCapabilities(network).hasTransport( + NetworkCapabilities.TRANSPORT_WIFI) + + doSomething(true, isWifi) + } + } + + override fun onLost(network: Network) { + lifecycleScope.launch { + Log.i("MainActivity", "onLost!") + doSomething(false) + } + } + } + ) + } + + } + + private suspend fun doSomething(isConnected:Boolean, isWifi:Boolean= false){ + withContext(Dispatchers.Main){ + if(isConnected) { + tvConnectivity.text = "Connected "+(if(isWifi)"WIFI" else "MOBILE") + tvConnectivity.setBackgroundColor(-0x8333da) + }else { + tvConnectivity.text = "Not Connected" + tvConnectivity.setBackgroundColor(-0x10000) + } + } + } +} diff --git a/android-connectivity/app/src/main/res/drawable/ic_launcher_background.xml b/android-connectivity/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..0d025f9b --- /dev/null +++ b/android-connectivity/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-connectivity/app/src/main/res/layout/activity_main.xml b/android-connectivity/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..5acf0117 --- /dev/null +++ b/android-connectivity/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,23 @@ + + + + + + \ No newline at end of file diff --git a/android-connectivity/app/src/main/res/values/colors.xml b/android-connectivity/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..69b22338 --- /dev/null +++ b/android-connectivity/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #008577 + #00574B + #D81B60 + diff --git a/android-connectivity/app/src/main/res/values/strings.xml b/android-connectivity/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..5bc6865a --- /dev/null +++ b/android-connectivity/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + connectivity + diff --git a/android-http/res/values/styles.xml b/android-connectivity/app/src/main/res/values/styles.xml similarity index 100% rename from android-http/res/values/styles.xml rename to android-connectivity/app/src/main/res/values/styles.xml diff --git a/android-connectivity/build.gradle b/android-connectivity/build.gradle new file mode 100644 index 00000000..e3245e7f --- /dev/null +++ b/android-connectivity/build.gradle @@ -0,0 +1,28 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.3.50' + repositories { + google() + jcenter() + + } + dependencies { + classpath 'com.android.tools.build:gradle:3.5.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android-http/build.gradle b/android-http/build.gradle new file mode 100644 index 00000000..e3245e7f --- /dev/null +++ b/android-http/build.gradle @@ -0,0 +1,28 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.3.50' + repositories { + google() + jcenter() + + } + dependencies { + classpath 'com.android.tools.build:gradle:3.5.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android-http/http-asynctask/build.gradle b/android-http/http-asynctask/build.gradle new file mode 100644 index 00000000..92493a00 --- /dev/null +++ b/android-http/http-asynctask/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.application' + +apply plugin: 'kotlin-android' + +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 29 + buildToolsVersion "29.0.2" + defaultConfig { + applicationId "com.hmkcode.http" + minSdkVersion 19 + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.0.2' + implementation 'androidx.core:core-ktx:1.0.2' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test:runner:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' +} diff --git a/android-http/http-asynctask/src/main/AndroidManifest.xml b/android-http/http-asynctask/src/main/AndroidManifest.xml new file mode 100644 index 00000000..964aa8b7 --- /dev/null +++ b/android-http/http-asynctask/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-http/http-asynctask/src/main/java/com/hmkcode/http/MainActivity.kt b/android-http/http-asynctask/src/main/java/com/hmkcode/http/MainActivity.kt new file mode 100644 index 00000000..8ad5ca04 --- /dev/null +++ b/android-http/http-asynctask/src/main/java/com/hmkcode/http/MainActivity.kt @@ -0,0 +1,103 @@ +package com.hmkcode.http + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkInfo +import android.os.AsyncTask +import android.os.Build +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.widget.TextView +import kotlinx.android.synthetic.main.activity_main.* +import java.io.BufferedReader +import java.io.InputStream +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL + +class MainActivity : AppCompatActivity() { + + lateinit var tvIsConnected: TextView; + lateinit var tvResult: TextView; + + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + tvIsConnected = findViewById(R.id.tvIsConnected) + tvResult = findViewById(R.id.tvResult) + + if(checkNetworkConnection()) + HTTPAsyncTask().execute("http://hmkcode-api.appspot.com/rest/api/hello/Android") + } + + + private fun checkNetworkConnection(): Boolean { + val cm:ConnectivityManager = + getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + val networkInfo:NetworkInfo? = cm.activeNetworkInfo + val isConnected: Boolean = if(networkInfo != null) networkInfo.isConnected() else false + + if(isConnected){ + tvIsConnected.setText("Connected "+networkInfo?.typeName) + tvIsConnected.setBackgroundColor(0xFF7CCC26.toInt()) + + }else{ + tvIsConnected.setText("Not Connected!") + tvIsConnected.setBackgroundColor(0xFFFF0000.toInt()) + } + return isConnected; + } + + inner class HTTPAsyncTask : AsyncTask() { + override fun doInBackground(vararg urls: String?): String { + return HttpGet(urls[0]) + } + override fun onPostExecute(result: String?) { + tvResult.setText(result) + } + } + + private fun HttpGet(myURL: String?): String { + + val inputStream:InputStream + val result:String + + // create URL + val url:URL = URL(myURL) + + // create HttpURLConnection + val conn:HttpURLConnection = url.openConnection() as HttpURLConnection + + // make GET request to the given URL + conn.connect() + + // receive response as inputStream + inputStream = conn.inputStream + + // convert inputstream to string + if(inputStream != null) + result = convertInputStreamToString(inputStream) + else + result = "Did not work!" + + return result + } + + private fun convertInputStreamToString(inputStream: InputStream): String { + val bufferedReader:BufferedReader? = BufferedReader(InputStreamReader(inputStream)) + var line:String? = bufferedReader?.readLine() + var result:String = "" + + while (line != null) { + result += line + line = bufferedReader?.readLine() + } + + inputStream.close() + return result + } + +} diff --git a/android-http/res/layout/activity_main.xml b/android-http/http-asynctask/src/main/res/layout/activity_main.xml similarity index 95% rename from android-http/res/layout/activity_main.xml rename to android-http/http-asynctask/src/main/res/layout/activity_main.xml index cb632171..fbab6354 100644 --- a/android-http/res/layout/activity_main.xml +++ b/android-http/http-asynctask/src/main/res/layout/activity_main.xml @@ -8,9 +8,7 @@ android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" - tools:context="com.hmkcode.android.http.MainActivity"> - - + tools:context="com.hmkcode.http.MainActivity"> + + #008577 + #00574B + #D81B60 + diff --git a/android-http/res/values/dimens.xml b/android-http/http-asynctask/src/main/res/values/dimens.xml similarity index 84% rename from android-http/res/values/dimens.xml rename to android-http/http-asynctask/src/main/res/values/dimens.xml index 47c82246..7b4d74af 100644 --- a/android-http/res/values/dimens.xml +++ b/android-http/http-asynctask/src/main/res/values/dimens.xml @@ -1,3 +1,4 @@ + 16dp diff --git a/android-http/http-asynctask/src/main/res/values/strings.xml b/android-http/http-asynctask/src/main/res/values/strings.xml new file mode 100644 index 00000000..03fc0f28 --- /dev/null +++ b/android-http/http-asynctask/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + android-http + diff --git a/android-http/http-asynctask/src/main/res/values/styles.xml b/android-http/http-asynctask/src/main/res/values/styles.xml new file mode 100644 index 00000000..5885930d --- /dev/null +++ b/android-http/http-asynctask/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/android-http/http-coroutine/build.gradle b/android-http/http-coroutine/build.gradle new file mode 100644 index 00000000..06e0675e --- /dev/null +++ b/android-http/http-coroutine/build.gradle @@ -0,0 +1,41 @@ +apply plugin: 'com.android.application' + +apply plugin: 'kotlin-android' + +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 29 + buildToolsVersion "29.0.2" + defaultConfig { + applicationId "com.hmkcode.http" + minSdkVersion 19 + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.core:core-ktx:1.0.2' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2" + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha05" + + + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test:runner:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' +} diff --git a/android-http/http-coroutine/src/main/AndroidManifest.xml b/android-http/http-coroutine/src/main/AndroidManifest.xml new file mode 100644 index 00000000..964aa8b7 --- /dev/null +++ b/android-http/http-coroutine/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-http/http-coroutine/src/main/java/com/hmkcode/http/MainActivity.kt b/android-http/http-coroutine/src/main/java/com/hmkcode/http/MainActivity.kt new file mode 100644 index 00000000..9403d24c --- /dev/null +++ b/android-http/http-coroutine/src/main/java/com/hmkcode/http/MainActivity.kt @@ -0,0 +1,116 @@ +package com.hmkcode.http + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkInfo +import android.os.AsyncTask +import android.os.Build +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.util.Log +import android.widget.TextView +import androidx.lifecycle.lifecycleScope +import kotlinx.android.synthetic.main.activity_main.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.InputStream +import java.io.InputStreamReader +import java.lang.Exception +import java.lang.NumberFormatException +import java.net.HttpURLConnection +import java.net.URL + +class MainActivity : AppCompatActivity() { + + lateinit var tvIsConnected: TextView; + lateinit var tvResult: TextView; + + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + tvIsConnected = findViewById(R.id.tvIsConnected) + tvResult = findViewById(R.id.tvResult) + + if(checkNetworkConnection()) { + lifecycleScope.launch { + val result = httpGet("http://hmkcode-api.appspot.com/rest/api/hello/Android") + tvResult.setText(result) + } + } + + } + + + private fun checkNetworkConnection(): Boolean { + + val cm:ConnectivityManager = + getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + + + val networkInfo:NetworkInfo? = cm.activeNetworkInfo + val isConnected: Boolean = if(networkInfo != null) networkInfo.isConnected() else false + + if(isConnected){ + tvIsConnected.setText("Connected "+networkInfo?.typeName) + tvIsConnected.setBackgroundColor(0xFF7CCC26.toInt()) + + }else{ + tvIsConnected.setText("Not Connected!") + tvIsConnected.setBackgroundColor(0xFFFF0000.toInt()) + } + return isConnected; + } + + + + private suspend fun httpGet(myURL: String?): String? { + + val result = withContext(Dispatchers.IO) { + val inputStream: InputStream + + + // create URL + val url: URL = URL(myURL) + + // create HttpURLConnection + val conn: HttpURLConnection = url.openConnection() as HttpURLConnection + + // make GET request to the given URL + conn.connect() + + // receive response as inputStream + inputStream = conn.inputStream + + // convert inputstream to string + if (inputStream != null) + convertInputStreamToString(inputStream) + else + "Did not work!" + + + } + return result + } + + private fun convertInputStreamToString(inputStream: InputStream): String { + val bufferedReader:BufferedReader? = BufferedReader(InputStreamReader(inputStream)) + + var line:String? = bufferedReader?.readLine() + var result:String = "" + + while (line != null) { + result += line + line = bufferedReader?.readLine() + } + + inputStream.close() + return result + } + +} diff --git a/android-http/http-coroutine/src/main/res/drawable/ic_launcher_background.xml b/android-http/http-coroutine/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..0d025f9b --- /dev/null +++ b/android-http/http-coroutine/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-http/http-coroutine/src/main/res/layout/activity_main.xml b/android-http/http-coroutine/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..fbab6354 --- /dev/null +++ b/android-http/http-coroutine/src/main/res/layout/activity_main.xml @@ -0,0 +1,36 @@ + + + + + + + diff --git a/android-http/http-coroutine/src/main/res/values/colors.xml b/android-http/http-coroutine/src/main/res/values/colors.xml new file mode 100644 index 00000000..69b22338 --- /dev/null +++ b/android-http/http-coroutine/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #008577 + #00574B + #D81B60 + diff --git a/android-http/http-coroutine/src/main/res/values/dimens.xml b/android-http/http-coroutine/src/main/res/values/dimens.xml new file mode 100644 index 00000000..7b4d74af --- /dev/null +++ b/android-http/http-coroutine/src/main/res/values/dimens.xml @@ -0,0 +1,6 @@ + + + + 16dp + 16dp + diff --git a/android-http/http-coroutine/src/main/res/values/strings.xml b/android-http/http-coroutine/src/main/res/values/strings.xml new file mode 100644 index 00000000..7ce813ab --- /dev/null +++ b/android-http/http-coroutine/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + android-http + + + Hello blank fragment + diff --git a/android-http/http-coroutine/src/main/res/values/styles.xml b/android-http/http-coroutine/src/main/res/values/styles.xml new file mode 100644 index 00000000..5885930d --- /dev/null +++ b/android-http/http-coroutine/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/android-http/java/com/hmkcode/android/http/MainActivity.java b/android-http/java/com/hmkcode/android/http/MainActivity.java deleted file mode 100644 index b459e2c6..00000000 --- a/android-http/java/com/hmkcode/android/http/MainActivity.java +++ /dev/null @@ -1,114 +0,0 @@ - package com.hmkcode.android.http; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.AsyncTask; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.util.Log; -import android.widget.TextView; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; - - public class MainActivity extends AppCompatActivity { - - TextView tvIsConnected; - TextView tvResult; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); - tvResult = (TextView) findViewById(R.id.tvResult); - if(checkNetworkConnection()) - // perform HTTP GET request - new HTTPAsyncTask().execute("http://hmkcode.com/examples/index.php"); - } - - - // check network connection - public boolean checkNetworkConnection() { - ConnectivityManager connMgr = (ConnectivityManager) - getSystemService(Context.CONNECTIVITY_SERVICE); - - NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); - boolean isConnected = false; - if (networkInfo != null && (isConnected = networkInfo.isConnected())) { - // show "Connected" & type of network "WIFI or MOBILE" - tvIsConnected.setText("Connected "+networkInfo.getTypeName()); - // change background color to red - tvIsConnected.setBackgroundColor(0xFF7CCC26); - - - } else { - // show "Not Connected" - tvIsConnected.setText("Not Connected"); - // change background color to green - tvIsConnected.setBackgroundColor(0xFFFF0000); - } - - return isConnected; - } - - private class HTTPAsyncTask extends AsyncTask { - @Override - protected String doInBackground(String... urls) { - - // params comes from the execute() call: params[0] is the url. - try { - return HttpGet(urls[0]); - } catch (IOException e) { - return "Unable to retrieve web page. URL may be invalid."; - } - } - // onPostExecute displays the results of the AsyncTask. - @Override - protected void onPostExecute(String result) { - tvResult.setText(result); - } - } - - private String HttpGet(String myUrl) throws IOException { - InputStream inputStream = null; - String result = ""; - - URL url = new URL(myUrl); - - // create HttpURLConnection - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - - // make GET request to the given URL - conn.connect(); - - // receive response as inputStream - inputStream = conn.getInputStream(); - - // convert inputstream to string - if(inputStream != null) - result = convertInputStreamToString(inputStream); - else - result = "Did not work!"; - - return result; - } - - private static String convertInputStreamToString(InputStream inputStream) throws IOException{ - BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); - String line = ""; - String result = ""; - while((line = bufferedReader.readLine()) != null) - result += line; - - inputStream.close(); - return result; - - } - - - } diff --git a/android-http/post-json/build.gradle b/android-http/post-json/build.gradle new file mode 100644 index 00000000..ae8be9dd --- /dev/null +++ b/android-http/post-json/build.gradle @@ -0,0 +1,42 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +android { + compileSdkVersion 29 + buildToolsVersion "29.0.2" + + + defaultConfig { + applicationId "com.hmkcodes" + minSdkVersion 19 + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'com.google.android.material:material:1.1.0-beta01' + implementation 'androidx.core:core-ktx:1.1.0' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2" + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha05" + + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test.ext:junit:1.1.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' +} diff --git a/android-http/post-json/src/main/AndroidManifest.xml b/android-http/post-json/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e84b4507 --- /dev/null +++ b/android-http/post-json/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-http/post-json/src/main/java/com/hmkcode/MainActivity.kt b/android-http/post-json/src/main/java/com/hmkcode/MainActivity.kt new file mode 100644 index 00000000..9cac05f8 --- /dev/null +++ b/android-http/post-json/src/main/java/com/hmkcode/MainActivity.kt @@ -0,0 +1,129 @@ +package com.hmkcode + +import android.content.Context +import android.net.ConnectivityManager +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.util.Log +import android.view.View +import android.widget.EditText +import android.widget.TextView +import android.widget.Toast +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONException +import org.json.JSONObject +import java.io.BufferedWriter +import java.io.IOException +import java.io.OutputStreamWriter +import java.net.HttpURLConnection +import java.net.URL +import javax.net.ssl.HttpsURLConnection + +class MainActivity : AppCompatActivity() { + + lateinit var tvIsConnected: TextView + lateinit var etTitle: EditText + lateinit var etUrl: EditText + lateinit var etTags: EditText + lateinit var tvResult: TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + tvIsConnected = findViewById(R.id.tvIsConnected) + etTitle = findViewById(R.id.etTitle) + etUrl = findViewById(R.id.etUrl) + etTags = findViewById(R.id.etTags) + tvResult = findViewById(R.id.tvResult) + checkNetworkConnection() + } + + public fun send(view:View) { + Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show() + // clear text result + tvResult.setText("") + + if (checkNetworkConnection()) + lifecycleScope.launch { + val result = httpPost("https://hmkcode-api.appspot.com/rest/link/add") + tvResult.setText(result) + } + else + Toast.makeText(this, "Not Connected!", Toast.LENGTH_SHORT).show() + + } + + @Throws(IOException::class, JSONException::class) + private suspend fun httpPost(myUrl: String): String { + + val result = withContext(Dispatchers.IO) { + val url = URL(myUrl) + // 1. create HttpURLConnection + val conn = url.openConnection() as HttpsURLConnection + conn.requestMethod = "POST" + conn.setRequestProperty("Content-Type", "application/json; charset=utf-8") + + // 2. build JSON object + val jsonObject = buidJsonObject() + + // 3. add JSON content to POST request body + setPostRequestContent(conn, jsonObject) + + // 4. make POST request to the given URL + conn.connect() + + // 5. return response message + conn.responseMessage + "" + } + return result + } + + private fun checkNetworkConnection(): Boolean { + val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + val networkInfo = connMgr.activeNetworkInfo + val isConnected: Boolean = if(networkInfo != null) networkInfo.isConnected() else false + if (networkInfo != null && isConnected) { + // show "Connected" & type of network "WIFI or MOBILE" + tvIsConnected.text = "Connected " + networkInfo.typeName + // change background color to red + tvIsConnected.setBackgroundColor(-0x8333da) + + + } else { + // show "Not Connected" + tvIsConnected.text = "Not Connected" + // change background color to green + tvIsConnected.setBackgroundColor(-0x10000) + } + + return isConnected + } + + @Throws(JSONException::class) + private fun buidJsonObject(): JSONObject { + + val jsonObject = JSONObject() + jsonObject.accumulate("title", etTitle.getText().toString()) + jsonObject.accumulate("url", etUrl.getText().toString()) + jsonObject.accumulate("tags", etTags.getText().toString()) + + return jsonObject + } + + @Throws(IOException::class) + private fun setPostRequestContent(conn: HttpURLConnection, jsonObject: JSONObject) { + + val os = conn.outputStream + val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8")) + writer.write(jsonObject.toString()) + Log.i(MainActivity::class.java.toString(), jsonObject.toString()) + writer.flush() + writer.close() + os.close() + } +} diff --git a/android-http/post-json/src/main/res/drawable/ic_launcher_background.xml b/android-http/post-json/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..0d025f9b --- /dev/null +++ b/android-http/post-json/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-http/post-json/src/main/res/layout/activity_main.xml b/android-http/post-json/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..157cdff1 --- /dev/null +++ b/android-http/post-json/src/main/res/layout/activity_main.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + +