Skip to content

Commit

Permalink
Merge pull request #9 from Kaiserdragon2/rework
Browse files Browse the repository at this point in the history
Include new Api for Api level > S
  • Loading branch information
Kaiserdragon2 authored Jul 10, 2024
2 parents 306615f + 96146c0 commit 4fcd21a
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 66 deletions.
15 changes: 4 additions & 11 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ android {
applicationId "de.kaiserdragon.callforwardingstatus"
minSdk 26
targetSdk 34
versionCode 5
versionName "1.7"
versionCode 6
versionName "1.8"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand All @@ -20,10 +20,6 @@ android {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
applicationIdSuffix '.debug'
versionNameSuffix '-DEBUG'
}
applicationVariants.all {
variant ->
variant.outputs.each {
Expand All @@ -45,10 +41,7 @@ android {

dependencies {

implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.appcompat:appcompat:1.7.0'
implementation 'com.google.android.material:material:1.12.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
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;
Expand All @@ -18,7 +19,9 @@

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 @@ -35,7 +38,7 @@ public void onReceive(Context context, Intent intent) {
} else
Toast.makeText(context, context.getString(R.string.NoNumber), Toast.LENGTH_SHORT).show();
}
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) {
Intent serviceIntent = new Intent(context, PhoneStateService.class);
context.startService(serviceIntent);
}
Expand All @@ -46,6 +49,7 @@ public int getSavedSelectedSimId(Context context) {
return preferences.getInt("SELECTED_SIM_ID", -1); // -1 is a default value if the preference is not found
}


private void setCallForwarding(Context context, boolean cfi, String phoneNumber) {
if (DEBUG) Log.i(TAG, String.valueOf(cfi));
if (DEBUG) Log.v(TAG, phoneNumber);
Expand All @@ -66,14 +70,16 @@ private void setCallForwarding(Context context, boolean cfi, String phoneNumber)
}
}
}
if (DEBUG) Log.v(TAG, String.valueOf(defaultSubId));


Handler handler = new Handler();
TelephonyManager.UssdResponseCallback responseCallback = new TelephonyManager.UssdResponseCallback() {
@Override
public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
super.onReceiveUssdResponse(telephonyManager, request, response);
Toast.makeText(context, response.toString(), Toast.LENGTH_SHORT).show();
Log.v(TAG, request);

}

@Override
Expand All @@ -86,7 +92,6 @@ public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, Strin
if (!cfi) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String ussdRequest = "*21*" + phoneNumber + "#";
if (DEBUG) Log.v(TAG, ussdRequest);

// Set the subscription ID for call forwarding
manager1 = manager.createForSubscriptionId(defaultSubId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package de.kaiserdragon.callforwardingstatus;

import static android.Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE;

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

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
Expand Down Expand Up @@ -105,7 +109,7 @@ protected void onCreate(Bundle savedInstanceState) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
saveSQLData(phoneNumber1EditText, 1);
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
inputManager.hideSoftInputFromWindow(Objects.requireNonNull(this.getCurrentFocus()).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
Expand All @@ -114,7 +118,7 @@ protected void onCreate(Bundle savedInstanceState) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
saveSQLData(phoneNumber2EditText, 2);
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
inputManager.hideSoftInputFromWindow(Objects.requireNonNull(this.getCurrentFocus()).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
Expand All @@ -123,7 +127,7 @@ protected void onCreate(Bundle savedInstanceState) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
saveSQLData(phoneNumber3EditText, 3);
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
inputManager.hideSoftInputFromWindow(Objects.requireNonNull(this.getCurrentFocus()).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
Expand Down Expand Up @@ -241,6 +245,7 @@ public void MultiSim(Context context) {
if (subscriptionManager != null) {
if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
List<SubscriptionInfo> subscriptionList = subscriptionManager.getActiveSubscriptionInfoList();
if (DEBUG) Log.i(TAG, String.valueOf(subscriptionList.size()));
if (subscriptionList.size() <= 1) {
findViewById(R.id.multisim_button).setVisibility(View.GONE);
} else findViewById(R.id.multisim_button).setOnClickListener(view -> showSimSelectionPopup(this));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package de.kaiserdragon.callforwardingstatus;

import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
import static de.kaiserdragon.callforwardingstatus.BuildConfig.DEBUG;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
Expand All @@ -20,7 +20,6 @@
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
Expand All @@ -29,19 +28,22 @@
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import de.kaiserdragon.callforwardingstatus.ForwardingStatusWidget;
import de.kaiserdragon.callforwardingstatus.R;
import kotlin.Deprecated;
import kotlin.Suppress;

public class PhoneStateService extends Service {
private static final String CHANNEL_ID = "CallForwardingServiceID";
public static boolean currentState;
Context context;
final String TAG = "Service";
static final String TAG = "Service";
private final Executor executor = Executors.newSingleThreadExecutor();
// Define NOTIFICATION_ID as a constant
private static final int NOTIFICATION_ID = 1;


/** @noinspection deprecation*/
@TargetApi(Build.VERSION_CODES.R)
private final PhoneStateListener phoneStateListener = new PhoneStateListener(executor) {
private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
if (DEBUG)Log.i(TAG, "onCallForwardingIndicatorChanged CFI Old=" + cfi);
Expand Down Expand Up @@ -69,80 +71,104 @@ public void onCallForwardingIndicatorChanged(boolean cfi) {
}
};


@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
createNotificationChannel();
startForegroundService();
registerPhoneStateListener();
}

// Create the notification channel
private void createNotificationChannel() {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Call Forwarding Service Channel",
getString(R.string.notification_channel_name), // Use string resources for text
NotificationManager.IMPORTANCE_DEFAULT
);

NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}

// Create a notification for the foreground service
private void startForegroundService() {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.NotificationTitle))
.setContentText(getString(R.string.NotificationText))
.setSmallIcon(R.drawable.ic_call_forwarding)
.build();

// Start the service as a foreground service
startForeground(1, notification);
context = this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE){
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.FOREGROUND_SERVICE_SPECIAL_USE)
== PackageManager.PERMISSION_GRANTED) {
startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
} else {
// Handle permission not granted (request permission, inform user, etc.)
Log.w(TAG, "FOREGROUND_SERVICE_SPECIAL_USE permission not granted");
// Consider gracefully stopping the service if this permission is critical
}
} else {
startForeground(NOTIFICATION_ID, notification);
}
}

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

// Register MyPhoneStateListener as a phone state listener
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
@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) {
registerCallForwardingIndicatorListener(telephonyManager);
MyCallForwardingListener listener = new MyCallForwardingListener();
telephonyManager.registerTelephonyCallback(Executors.newSingleThreadExecutor(), listener);
if (DEBUG) Log.i(TAG, "Registered TelephonyCallback");
} else {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
if (DEBUG) Log.i(TAG, "Registered PhoneStateListener");
}
}

//todo new api does not work right
@RequiresApi(api = Build.VERSION_CODES.S)
private void registerCallForwardingIndicatorListener(TelephonyManager telephonyManager) {
// New API (API level 31 and above)
TelephonyCallback callback = new TelephonyCallback();
TelephonyCallback.CallForwardingIndicatorListener callForwardingListener =
cfi -> {
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);
};
// Register the TelephonyCallback
//telephonyManager.registerTelephonyCallback(executor,callForwardingListener);
}
@Override
@SuppressWarnings("deprecation")
public void onDestroy() {
super.onDestroy();
// Unregister MyPhoneStateListener as a phone state listener
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);
super.onDestroy();
// Unregister MyPhoneStateListener as a phone state listener
}

@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);

}
}
}
1 change: 1 addition & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@
<string name="callForwarding">Rufumleitung</string>
<string name="applyColor">Farbe anwenden</string>
<string name="select_sim">Wähle eine SIM</string>
<string name="notification_channel_name">Rufumleitung</string>
</resources>
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@
<string name="callForwarding">CallForwarding</string>
<string name="applyColor">Apply Color</string>
<string name="select_sim">Select Simcard</string>
<string name="notification_channel_name">CallForwarding</string>
</resources>
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.1.0'
classpath 'com.android.tools.build:gradle:8.5.0'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

task clean(type: Delete) {
tasks.register('clean', Delete) {
delete rootProject.buildDir
}
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Sun Jan 16 11:54:38 CET 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

0 comments on commit 4fcd21a

Please sign in to comment.