Reputation: 641
I want to do something when user copied something to clipboard and i know there is an event in the ClipboardManager
like this:
class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener
{
public void onPrimaryClipChanged()
{
// use getPrimaryClip() to get the data or simply display a toast
}
}
ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener() );
but i want to know how to get notified when my app is closed by user and then user for example copied something from another app to clipboard.
Should i use Service
, If so which one?
Upvotes: 4
Views: 3644
Reputation: 77
Unfortunately since Android 10 (Q) Google has removed the option of background apps to listen to ClipboardManager changes.
You can still listen to ClipboardManager changes but only from the main thread.
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.
Upvotes: 2
Reputation: 377
First, You need to add these permissions to AndroidManifest:
<uses-permission android:name="android.permission.GET_CLIPS" />
<uses-permission android:name="android.permission.READ_CLIPS" />
<uses-permission android:name="android.permission.WRITE_CLIPS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Then, you need to add a service like this:
public class Clipboard extends Service {
private ClipboardManager mCM;
IBinder mBinder;
int mStartMode;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mCM.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
String newClip = mCM.getText().toString();
Toast.makeText(getApplicationContext(), newClip.toString(), Toast.LENGTH_LONG).show();
Log.i("LOG", newClip.toString() + "");
}
});
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Add this service in AndroidManifest:
<service android:name=".Clipboard" />
start service at MainActivity
startService(new Intent(this, Clipboard.class));
Upvotes: 5