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.
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 ....
}
what does "mainactivity is not active" mean? you are getting access to
ClipboardManager
insideOnClickListener
attached toButton
, which is aView
and needContext
, so there must be aliveActivity
, which keeps thisButton
on the screen for clicking purpose...btw. maybe you are you checking on Android 10 or above? it looks like according to docs
privacy/security reasons, thats how it will be working now