Skip to content

Commit

Permalink
Merge pull request #12 from Kaiserdragon2/rework
Browse files Browse the repository at this point in the history
Hopfully service now runs stable in the Background
  • Loading branch information
Kaiserdragon2 authored Jul 14, 2024
2 parents 7c3d446 + d49b5a0 commit aa1fe0d
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 81 deletions.
8 changes: 5 additions & 3 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ android {

defaultConfig {
applicationId "de.kaiserdragon.callforwardingstatus"
minSdk 26
minSdk 28
targetSdk 34
versionCode 6
versionName "1.8"
versionCode 7
versionName "1.9"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand Down Expand Up @@ -50,4 +50,6 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.7.0'
implementation 'com.google.android.material:material:1.12.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation("androidx.work:work-runtime-ktx:2.9.0")
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package de.kaiserdragon.callforwardingstatus;

import static android.content.Context.TELEPHONY_SERVICE;
import static androidx.core.content.ContextCompat.getSystemService;
import static de.kaiserdragon.callforwardingstatus.BuildConfig.DEBUG;

import android.Manifest;
import android.content.BroadcastReceiver;
Expand All @@ -19,10 +17,10 @@

import androidx.core.app.ActivityCompat;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;


public class CallForwardingReceiver extends BroadcastReceiver {
final String TAG = "Receiver";

Expand All @@ -31,8 +29,9 @@ public void onReceive(Context context, Intent intent) {
if ("de.kaiserdragon.callforwardingstatus.TOGGLE_CALL_FORWARDING".equals(intent.getAction())) {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
String[] array = databaseHelper.getSelected();
if (DEBUG) Log.v(TAG, "Number = " + array[1]);
if (!array[1].equals("")) {
databaseHelper.close();
//if (DEBUG) Log.v(TAG, "Number = " + array[1]);
if (!array[1].isEmpty()) {
Toast.makeText(context, context.getString(R.string.setupCallForwarding), Toast.LENGTH_LONG).show();
setCallForwarding(context, PhoneStateService.currentState, array[1]);
} else
Expand All @@ -51,8 +50,8 @@ public int getSavedSelectedSimId(Context context) {


private void setCallForwarding(Context context, boolean cfi, String phoneNumber) {
if (DEBUG) Log.i(TAG, String.valueOf(cfi));
if (DEBUG) Log.v(TAG, phoneNumber);
//if (DEBUG) Log.i(TAG, String.valueOf(cfi));
//if (DEBUG) Log.v(TAG, phoneNumber);
TelephonyManager manager = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);

int defaultSubId = getSavedSelectedSimId(context);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package de.kaiserdragon.callforwardingstatus;


import static android.content.Context.MODE_PRIVATE;

import static de.kaiserdragon.callforwardingstatus.BuildConfig.DEBUG;
Expand Down Expand Up @@ -84,13 +83,15 @@ public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidge
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
load(context);
//load(context);
Log.v(TAG,"onReceive got called");
if ("de.kaiserdragon.callforwardingstatus.APPWIDGET_UPDATE_CFI".equals(intent.getAction())) {
// Get the current CFI value from the Intent extra
currentState = intent.getBooleanExtra("cfi", currentState);
if(DEBUG)Log.v(TAG,"CFI:"+currentState);
//currentState = cfi;

save(context);
PhoneStateService.currentState = currentState;
//save(context);
// Update the widget with the current CFI value
updateWidget(context, currentState);
}
Expand Down Expand Up @@ -163,10 +164,7 @@ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] a
if (DEBUG) Log.v(TAG,"onUpdate got called");
Intent serviceIntent = new Intent(context, PhoneStateService.class);
context.startForegroundService(serviceIntent);
load(context);
updateWidget(context, currentState);


}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package de.kaiserdragon.callforwardingstatus;

import static android.Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE;

import static de.kaiserdragon.callforwardingstatus.BuildConfig.DEBUG;

import android.Manifest;
Expand Down Expand Up @@ -237,7 +235,7 @@ private void setCheckedRadioButton() {
if (Objects.equals(array[0], "1")) radioButton1.setChecked(true);
if (Objects.equals(array[0], "2")) radioButton2.setChecked(true);
if (Objects.equals(array[0], "3")) radioButton3.setChecked(true);
Log.i(TAG, "Retrieve Data" + array[0] + "phone" + array[1]);
//Log.i(TAG, "Retrieve Data" + array[0] + "phone" + array[1]);
}

public void MultiSim(Context context) {
Expand Down Expand Up @@ -292,7 +290,7 @@ public int getSavedSelectedSimId(Context context) {

private String getPhoneNumber(int row) {
// Query the database to retrieve the data
Log.i(TAG, "Retrieve Data");
//Log.i(TAG, "Retrieve Data");
SQLiteDatabase database = databaseHelper.getReadableDatabase();
String[] columns = {databaseHelper.getColumnPhoneNumber()};
String selection = databaseHelper.getColumnId() + " = ?";
Expand Down Expand Up @@ -494,7 +492,6 @@ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permis
public class SimSelectionDialog extends AlertDialog {
private final List<SubscriptionInfo> subscriptionList;
private ListView listView;
private ArrayAdapter<String> adapter;

protected SimSelectionDialog(Context context, List<SubscriptionInfo> subscriptionList) {
super(context);
Expand All @@ -505,7 +502,7 @@ protected SimSelectionDialog(Context context, List<SubscriptionInfo> subscriptio
private void init() {
Context context = getContext();
listView = new ListView(context);
adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice);
ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice);
for (SubscriptionInfo subscriptionInfo : subscriptionList) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
String displayName = subscriptionInfo.getDisplayName().toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,32 @@
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import kotlin.Deprecated;
import kotlin.Suppress;
import de.kaiserdragon.callforwardingstatus.helper.CallForwardingListener;

public class PhoneStateService extends Service {
private static final String CHANNEL_ID = "CallForwardingServiceID";
public static boolean currentState;
Context context;
Context appcontext;
static final String TAG = "Service";
private final Executor executor = Executors.newSingleThreadExecutor();

// Define NOTIFICATION_ID as a constant
private static final int NOTIFICATION_ID = 1;
private CallForwardingListener callForwardingListener;


/** @noinspection deprecation*/
Expand All @@ -47,24 +43,16 @@ public class PhoneStateService extends Service {
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
if (DEBUG)Log.i(TAG, "onCallForwardingIndicatorChanged CFI Old=" + cfi);
// Get the current state of unconditional call forwarding
currentState = cfi;
// Create an Intent with the android.appwidget.action.APPWIDGET_UPDATE action
Intent intent = new Intent(context, ForwardingStatusWidget.class);
Intent intent = new Intent(appcontext, ForwardingStatusWidget.class);
intent.setAction("de.kaiserdragon.callforwardingstatus.APPWIDGET_UPDATE_CFI");
//Toast.makeText(context, "OLD", Toast.LENGTH_SHORT).show();
// Add the app widget IDs as an extra
int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), ForwardingStatusWidget.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);

// Add the CFI value as an extra
intent.putExtra("cfi", currentState);

intent.putExtra("cfi", cfi);
// Send the broadcast
sendBroadcast(intent);

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(appcontext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
super.onCallForwardingIndicatorChanged(cfi);
}
}
Expand All @@ -74,10 +62,10 @@ public void onCallForwardingIndicatorChanged(boolean cfi) {
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
appcontext = getApplicationContext();
createNotificationChannel();
startForegroundService();
registerPhoneStateListener();

}

private void createNotificationChannel() {
Expand All @@ -99,7 +87,7 @@ private void startForegroundService() {
.build();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE){
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE)
if (ActivityCompat.checkSelfPermission(appcontext, Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE)
== PackageManager.PERMISSION_GRANTED) {
startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
} else {
Expand All @@ -114,61 +102,44 @@ private void startForegroundService() {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerPhoneStateListener();
return START_STICKY;
}

@SuppressWarnings("deprecation")
private void registerPhoneStateListener() {
TelephonyManager telephonyManager = getSystemService(TelephonyManager.class); // Use class reference for type safety
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
MyCallForwardingListener listener = new MyCallForwardingListener();
telephonyManager.registerTelephonyCallback(Executors.newSingleThreadExecutor(), listener);
if (DEBUG) Log.i(TAG, "Registered TelephonyCallback");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
if (callForwardingListener == null) { // Check if already registered
callForwardingListener = new CallForwardingListener(appcontext);
telephonyManager.registerTelephonyCallback(Executors. newSingleThreadExecutor(), callForwardingListener);
if (DEBUG) Log.i(TAG, "Registered TelephonyCallback");
}
} else {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
if (DEBUG) Log.i(TAG, "Registered PhoneStateListener");
//if (DEBUG) Log.i(TAG, "Registered PhoneStateListener");
}
}

@Override
@SuppressWarnings("deprecation")
public void onDestroy() {
Log.d(TAG,"Destroy");
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S) telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
Log.d(TAG, "Destroy");
TelephonyManager telephonyManager = getSystemService(TelephonyManager.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&callForwardingListener != null) {
telephonyManager.unregisterTelephonyCallback(callForwardingListener); // Unregister explicitly
callForwardingListener = null;
if (DEBUG) Log.i(TAG, "Unregistered TelephonyCallback");
} else {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
// Unregister MyPhoneStateListener as a phone state listener
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
// Return null as this service is not bound to any activity
return null;
}

@RequiresApi(api = Build.VERSION_CODES.S)
public class MyCallForwardingListener extends TelephonyCallback implements TelephonyCallback.CallForwardingIndicatorListener {
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
// Handle the call forwarding state change here
if (DEBUG) Log.i(TAG, "onCallForwardingIndicatorChanged CFI New=" + cfi);
// Get the current state of unconditional call forwarding
//Toast.makeText(context, "New", Toast.LENGTH_SHORT).show();
currentState = cfi;
// Create an Intent with the android.appwidget.action.APPWIDGET_UPDATE action
Intent intent = new Intent(context, ForwardingStatusWidget.class);
intent.setAction("de.kaiserdragon.callforwardingstatus.APPWIDGET_UPDATE_CFI");

// Add the app widget IDs as an extra
int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), ForwardingStatusWidget.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);

// Add the CFI value as an extra
intent.putExtra("cfi", currentState);

// Send the broadcast
sendBroadcast(intent);

}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package de.kaiserdragon.callforwardingstatus;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.ListenableWorker;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class PhoneStateWorker extends Worker {
public PhoneStateWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}

@NonNull
@Override
public Result doWork() {
return null;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package de.kaiserdragon.callforwardingstatus.helper;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.telephony.TelephonyCallback;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import java.lang.ref.WeakReference;

import de.kaiserdragon.callforwardingstatus.BuildConfig;
import de.kaiserdragon.callforwardingstatus.ForwardingStatusWidget;
import de.kaiserdragon.callforwardingstatus.PhoneStateService;

@RequiresApi(api = Build.VERSION_CODES.S)
public class CallForwardingListener extends TelephonyCallback implements TelephonyCallback.CallForwardingIndicatorListener {

private static final String TAG = "CallForwardingListener";
private static WeakReference<Context> contextRef;

public CallForwardingListener(@NonNull Context context) {
contextRef = new WeakReference<>(context);
}

@Override
public void onCallForwardingIndicatorChanged(boolean callForwardingIndicator) {

if (BuildConfig.DEBUG) {
Log.i(TAG, "onCallForwardingIndicatorChanged - New CFI (different from last): " + callForwardingIndicator);

PhoneStateService.currentState = callForwardingIndicator;
sendWidgetUpdateBroadcast(callForwardingIndicator);
}

}

private void sendWidgetUpdateBroadcast(boolean callForwardingIndicator) {
Context context = contextRef.get();
Intent intent = new Intent(context, ForwardingStatusWidget.class);
intent.setAction("de.kaiserdragon.callforwardingstatus.APPWIDGET_UPDATE_CFI");
// Add the CFI value as an extra
intent.putExtra("cfi", callForwardingIndicator);
// Send the broadcast
context.sendBroadcast(intent);
}
}

0 comments on commit aa1fe0d

Please sign in to comment.