How To Access The Clipboard On Android Device
Solution 1:
Android system only allow us to activate one Activity
at a time, and the others are in onPause()
state. Starting an activity should have a layout.xml
, and must call startActivity(Intent)
.
From the logcat:
"java.lang.IllegalStateException: System services not available to Activities before onCreate()".
We can know that getSystemService()
only available after super.onCreate(Bundle)
, which triggers the activity to be created.
A good practice to call getSystemService()
in non-activity class is by passing Context
parameter to GetClipBoard
's constructor and make it as public
:
public class GetClipBoard extends AsyncTask<Void, Void, String> {
private Context context;
public GetClipBoard(Context context){
this.context = context;
}
private String pMyClip;
@Override
protected String doInBackground(Void...params) {
try {
// ClipboardManager p = params[0];
String pasteData = "";
ClipboardManager myClipBoard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
...
}catch (Exception e){
...
}
// Gets the clipboard as text.
return pMyClip;
}
...
}
So once you executing AsyncTask
, call the class from Android components that has Context
, e.g. Activity
, Service
, BroadcastReceiver
, etc.
new GetClipBoard(this).execute(); // 'this' > context
Solution 2:
I believe that is my issue, currently I don't think I have a component that has Context. This is the class I am making the call from (part of it) and the first class that is being called by adb runtest.
public class SetupApp extends UiAutomatorTestCase {
public void testAppSetup() throws UiObjectNotFoundException, RemoteException
{
//other code here
MyClipBoard myBoard = new MyClipBoard();
myBoard.getClipBoard();
Post a Comment for "How To Access The Clipboard On Android Device"