Skip to content

Commit

Permalink
Use WorkManager instead of AsyncTask, change min sdk version, some re…
Browse files Browse the repository at this point in the history
…factoring
  • Loading branch information
Konstantin Bogomolov committed Jun 5, 2021
1 parent 4723772 commit fc49d76
Show file tree
Hide file tree
Showing 9 changed files with 204 additions and 104 deletions.
8 changes: 6 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ android {

defaultConfig {
applicationId "tech.bogomolov.incomingsmsgateway"
minSdkVersion 16
targetSdkVersion 29
minSdkVersion 19
targetSdkVersion 30
versionCode 5
versionName "1.1"

Expand All @@ -27,13 +27,16 @@ android {
}

dependencies {
def work_version = "2.4.0"

implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.0.0'
implementation 'androidx.navigation:navigation-ui:2.0.0'
implementation "androidx.work:work-runtime:$work_version"

testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:3.7.0'
Expand All @@ -42,4 +45,5 @@ dependencies {
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation "org.mockito:mockito-android:3.7.0"
androidTestImplementation 'androidx.test:rules:1.3.0'
androidTestImplementation "androidx.work:work-testing:$work_version"
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,13 @@

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.ViewInteraction;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,65 @@
package tech.bogomolov.incomingsmsgateway;

import android.content.Context;
import android.util.Log;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.work.Configuration;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;
import androidx.work.testing.SynchronousExecutor;
import androidx.work.testing.WorkManagerTestInitHelper;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
public class WebhookCallerTest {

@Test
public void testSuccess() {
WebhookCaller webhookCaller = new WebhookCaller();
String result = webhookCaller.doInBackground("https://example.com", "test");
@Before
public void setup() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Configuration config = new Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(new SynchronousExecutor())
.build();

assertEquals(result, WebhookCaller.RESULT_SUCCESS);
WorkManagerTestInitHelper.initializeTestWorkManager(
context, config);
}

@Test
public void testError() {
WebhookCaller webhookCaller = new WebhookCaller();
String result = webhookCaller.doInBackground("not a url", "test");

assertEquals(result, WebhookCaller.RESULT_ERROR);
public void testSuccess() throws Exception {
WorkInfo workInfo = this.getWorkInfo("https://example.com", "test");
assertThat(workInfo.getState(), is(WorkInfo.State.SUCCEEDED));
}

@Test
public void testConnectionError() {
WebhookCaller webhookCaller = new WebhookCaller();
String result = webhookCaller.doInBackground("https://urlisnotexisterrortest.ee", "test");
public void testError() throws Exception {
WorkInfo workInfo = this.getWorkInfo("not a url", "test");
assertThat(workInfo.getState(), is(WorkInfo.State.FAILED));
}

private WorkInfo getWorkInfo(String url, String text) throws Exception {
Data input = new Data.Builder()
.put(WebHookWorkRequest.DATA_URL, url)
.put(WebHookWorkRequest.DATA_TEXT, text)
.build();

OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(WebHookWorkRequest.class)
.setInputData(input)
.build();

assertEquals(result, WebhookCaller.RESULT_CONNECTION_ERROR);
WorkManager workManager = WorkManager.getInstance(getApplicationContext());
workManager.enqueue(request).getResult().get();
return workManager.getWorkInfoById(request.getId()).get();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,30 @@
import java.util.ArrayList;
import java.util.Map;

public class Config {
public class ForwardingConfig {
final private Context context;

private String sender;
private String url;

public Config(Context context) {
public ForwardingConfig(Context context) {
this.context = context;
}

public String getSender() {
return this.sender;
}

public Config setSender(String sender) {
public void setSender(String sender) {
this.sender = sender;
return this;
}

public String getUrl() {
return this.url;
}

public Config setUrl(String url) {
public void setUrl(String url) {
this.url = url;
return this;
}

public void save() {
Expand All @@ -40,14 +38,14 @@ public void save() {
editor.commit();
}

public static ArrayList<Config> getAll(Context context) {
public static ArrayList<ForwardingConfig> getAll(Context context) {
SharedPreferences sharedPref = getPreference(context);
Map<String, ?> sharedPrefs = sharedPref.getAll();

ArrayList<Config> configs = new ArrayList<Config>();
ArrayList<ForwardingConfig> configs = new ArrayList<ForwardingConfig>();

for (Map.Entry<String, ?> entry : sharedPrefs.entrySet()) {
Config config = new Config(context);
ForwardingConfig config = new ForwardingConfig(context);
config.setSender(entry.getKey());
config.setUrl((String) entry.getValue());
configs.add(config);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

import java.util.ArrayList;

public class ListAdapter extends ArrayAdapter<Config> {
final private ArrayList<Config> dataSet;
public class ListAdapter extends ArrayAdapter<ForwardingConfig> {
final private ArrayList<ForwardingConfig> dataSet;
Context context;

public ListAdapter(ArrayList<Config> data, Context context) {
public ListAdapter(ArrayList<ForwardingConfig> data, Context context) {
super(context, R.layout.list_item, data);
this.dataSet = data;
this.context = context;
Expand All @@ -34,7 +34,7 @@ public View getView(int position, View convertView, ViewGroup parent) {
row = inflater.inflate(R.layout.list_item, parent, false);
}

Config config = getItem(position);
ForwardingConfig config = getItem(position);

String senderText = config.getSender();
String asterisk = context.getString(R.string.asterisk);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

Expand All @@ -29,7 +28,7 @@ public class MainActivity extends AppCompatActivity {

public void onDeleteClick(View view) {
final int position = (int) view.getTag(R.id.delete_button);
final Config config = listAdapter.getItem(position);
final ForwardingConfig config = listAdapter.getItem(position);

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.delete_record);
Expand Down Expand Up @@ -60,7 +59,7 @@ protected void onCreate(Bundle savedInstanceState) {
context = this;
ListView listview = findViewById(R.id.listView);

ArrayList<Config> configs = Config.getAll(context);
ArrayList<ForwardingConfig> configs = ForwardingConfig.getAll(context);
listAdapter = new ListAdapter(configs, context);

listview.setAdapter(listAdapter);
Expand Down Expand Up @@ -104,7 +103,7 @@ public void onClick(View view) {
return;
}

Config config = new Config(context);
ForwardingConfig config = new ForwardingConfig(context);
config.setSender(sender);
config.setUrl(url);
config.save();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,27 @@
import android.telephony.SmsMessage;
import android.util.Log;

import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class SmsReceiver extends BroadcastReceiver {

private Context context;

@Override
public void onReceive(Context context, Intent intent) {
this.context = context;

Bundle bundle = intent.getExtras();
if (bundle == null) {
return;
Expand All @@ -25,14 +39,14 @@ public void onReceive(Context context, Intent intent) {
return;
}

ArrayList<Config> configs = Config.getAll(context);
ArrayList<ForwardingConfig> configs = ForwardingConfig.getAll(context);
String asterisk = context.getString(R.string.asterisk);

for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String sender = message.getOriginatingAddress();

for (Config config : configs) {
for (ForwardingConfig config : configs) {
if (sender.equals(config.getSender()) || config.getSender().equals(asterisk)) {
JSONObject messageJson = this.prepareMessage(sender, message.getMessageBody());

Expand All @@ -44,7 +58,31 @@ public void onReceive(Context context, Intent intent) {
}

protected void callWebHook(String url, String message) {
new WebhookCaller().execute(url, message);

Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();

Data data = new Data.Builder()
.putString(WebHookWorkRequest.DATA_URL, url)
.putString(WebHookWorkRequest.DATA_TEXT, message)
.build();

WorkRequest webhookWorkRequest =
new OneTimeWorkRequest.Builder(WebHookWorkRequest.class)
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.setInputData(data)
.build();

WorkManager
.getInstance(this.context)
.enqueue(webhookWorkRequest);

}

private JSONObject prepareMessage(String sender, String message) {
Expand Down
Loading

0 comments on commit fc49d76

Please sign in to comment.