user15549225
user15549225

Reputation: 1

Update old Android WebView app to new with target SDK 34

I am a PHP developer and I have basic knowledge of Android. I have an Android webview app with targetSdk 33 and I built it with older Android studio version with some popular features like push notification, swiper screen refresh, splash screen, web upload, web url redirect to browser etc which you can see in shared code.

But now I want to build it with targetSdk 34 or 35. But when I am trying to open it with latest Android studio I am not able to open it. And I don't know much about Android so I am unable to update this code or create any new app for this. How to convert this app to new environment with more new and latest features?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="TestApp.in">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <permission
        android:name="TestApp.in.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="TestApp.in.permission.C2D_MESSAGE" />

    <uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>

    <application
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:remove="android:appComponentFactory"
        tools:replace="android:icon">

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"
            android:exported="true"/>
        <activity
            android:name=".SplashScreen"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Firebase Notifications -->
        <service
            android:name=".FCM.MyFirebaseMessagingService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service
            android:name=".FCM.MyFirebaseInstanceIDService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- ./Firebase Notifications -->

    </application>

</manifest>

MyFirebaseInstanceIDService.java

package TestApp.in.FCM;

import android.content.Intent;
import android.content.SharedPreferences;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import TestApp.in.Config;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}

CustomWebview.java

package TestApp.in;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebView;

/**
 * Created by TestApp in
 */

public class CustomWebview extends WebView {

    public CustomWebview(Context context) {
        super(context);
    }

    public CustomWebview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomWebview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onCheckIsTextEditor() {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)     {
        switch (ev.getAction())         {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!hasFocus())
                    requestFocus();
                break;
        }

        return super.onTouchEvent(ev);
    }
}
                

DetectConnection.java

package TestApp.in;

import android.content.Context;
import android.net.ConnectivityManager;


public class DetectConnection {             
  public static boolean checkInternetConnection(Context context) {   

    ConnectivityManager con_manager = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (con_manager.getActiveNetworkInfo() != null
        && con_manager.getActiveNetworkInfo().isAvailable()
        && con_manager.getActiveNetworkInfo().isConnected()) {
      return true;
    } else {
      return false;
    }
  }
}

MainActivity.java

package TestApp.in;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import com.google.android.material.snackbar.Snackbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.firebase.analytics.FirebaseAnalytics;

import TestApp.in.Fragments.WebViewFragment;


public class MainActivity extends AppCompatActivity  {


    private BroadcastReceiver mRegistrationBroadcastReceiver;
    boolean doubleBackToExitPressedOnce = false;
    private FirebaseAnalytics mFirebaseAnalytics;
    RelativeLayout rel_layout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //ButterKnife.bind(this);
        rel_layout=(RelativeLayout)findViewById(R.id.rel_layout);
        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        Bundle bundle = new Bundle();
        WebViewFragment webViewFragment = new WebViewFragment();
        bundle.putString("url", Config.homeUrl);
        webViewFragment.setArguments(bundle);
        loadFragment(webViewFragment, false,"webViewFragment");
        try {
            Intent intent = getIntent();
            String message = intent.getStringExtra("message");
            String url = intent.getStringExtra("url");
            Log.d("notification Data", message + url);
            if (url.length() > 0) {
                bundle.putString("url", url);
                webViewFragment.setArguments(bundle);
                loadFragment(webViewFragment, false,"webViewFragment");

            }
        } catch (Exception e) {
            Log.d("error notification data", e.toString());
        }
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        displayFirebaseRegId();
    }


    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e("FCM", "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId)) {
//            txtRegId.setText("Firebase Reg Id: " + regId);
        } else
            Log.d("Firebase", "Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {

        Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
        if(fragment!=null && fragment instanceof WebViewFragment){
            if(((WebViewFragment) fragment).onBackPressed()){
                if (doubleBackToExitPressedOnce) {
                    super.onBackPressed();
                    return;
                }

                this.doubleBackToExitPressedOnce = true;
                // Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show();
                Snackbar snackbar = Snackbar
                        .make(rel_layout, "Press back once more to exit", Snackbar.LENGTH_LONG);
                snackbar.setActionTextColor(Color.RED);
                View snackbarView = snackbar.getView();
                snackbarView.setBackgroundColor(Color.DKGRAY);
                TextView textView = (TextView) snackbarView.findViewById(R.id.snackbar_text);
                textView.setTextColor(Color.YELLOW);
                snackbar.show();

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        doubleBackToExitPressedOnce = false;
                    }
                }, 2000);
            }
        }

    }

    public void loadFragment(Fragment fragment, Boolean bool) {
        loadFragment(fragment, bool,null);
    }
    public void loadFragment(Fragment fragment, Boolean bool, String TAG) {
        showAds();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(TAG == null) {
            transaction.replace(R.id.frameLayout, fragment);
        }else {
            transaction.replace(R.id.frameLayout,fragment,TAG);
        }
        if (bool)
            transaction.addToBackStack(null);
        transaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){

        Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
        if(fragment!=null && fragment instanceof WebViewFragment){
            ((WebViewFragment)fragment).onActivityResult(requestCode, resultCode, intent);
        }
        super.onActivityResult(requestCode, resultCode, intent);

    }

    public void hideAds(){
    }

    public void showAds(){
    }
}

SplashScreen.java

package TestApp.in;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;

public class SplashScreen extends AppCompatActivity {


    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
String message="",url="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        try {
            Intent intent = getIntent();
             message = intent.getStringExtra("message");
             url = intent.getStringExtra("url");
            Log.d("notification Data", message + url);
        }catch (Exception e)
        {
            Log.d("error notification data",e.toString());
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                intent.putExtra("message",message);
                intent.putExtra("url",url);
                startActivity(intent);
                finish();
            }
        });
        thread.start();
    }

}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 33

    defaultConfig {
        applicationId "TestApp.in"
        minSdkVersion 22
        targetSdkVersion 33
        versionCode 7
        versionName '1.7'
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    repositories {
        mavenCentral()
        google()
    }
    dexOptions {
        jumboMode = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in releas builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    //noinspection GradleCompatible
    implementation 'androidx.appcompat:appcompat:1.6.1'
    //implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.jakewharton:butterknife:10.0.0'
    //implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.3.2'
    //implementation 'com.android.support:design:27.1.0'
    implementation 'com.google.android.material:material:1.6.0'
    implementation 'com.squareup.retrofit:retrofit:1.9.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.google.firebase:firebase-messaging:21.1.0'
    implementation 'com.google.firebase:firebase-core:21.1.1'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
    testImplementation 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

Upvotes: 0

Views: 51

Answers (0)

Related Questions