Clipboard data returns null when MainActivity is not active in top view activity when I click the button in Android java

I read this restriction about android10 and higher, but my activity is not a background service. I need to get clipboard data when I click on the button located in the top view activity like the Google Translate application. In my case, the clipboard returns null when MainActivity is not active.

Google translate https://developer.android.com/about/versions/10/privacy/changes#clipboard-data

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initializes the Bridge
        this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
          // Additional plugins you've installed go here
          // Ex: add(TotallyAwesomePlugin.class);
        }});
        
        startActivity(new Intent(MainActivity.this, FloatingWindow.class));
    }
}



public class FloatingWindow extends Activity {
// ... additional code ....
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        floatingButtonDefinedInClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    self.getClipboardText(); 
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    public void getClipboardText() throws IOException {
        try {
            ClipboardManager myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = myClipboard.getPrimaryClip();
            if(clipData != null) {
                text = (String) clipData.getItemAt(0).getText();
                System.out.println(text); // returns null when mainactivity is not active 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    
// ... additional code ....
}
1

There are 1 answers

6
snachmsm On

what does "mainactivity is not active" mean? you are getting access to ClipboardManager inside OnClickListener attached to Button, which is a View and need Context, so there must be alive Activity, which keeps this Button on the screen for clicking purpose...

btw. maybe you are you checking on Android 10 or above? it looks like according to docs

Limited access to clipboard data

Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher.

privacy/security reasons, thats how it will be working now