I want to open my application and display copied text whenever i have copied the text from anywhere in android. how can i do this?
public class MainActivity extends Activity
{
Button paste;
TextView display;
private ClipData clipdata;
private android.content.ClipboardManager mgr;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paste = (Button) findViewById(R.id.paste);
display = (TextView) findViewById(R.id.textView1);
mgr = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
paste.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
try
{
clipdata = mgr.getPrimaryClip();
ClipData.Item item = clipdata.getItemAt(0);
String text = item.getText().toString();
display.setText(display.getText() + "\n" + text);
Toast.makeText(getApplicationContext(), "Text Pasted",
Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"Error : " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
Following is a working code which launches your app whenever you copy something anywhere else, it uses a ClipboardMonitorService service running in background when the app is first launched:
In Manifest.xml put following line under <application>
tag :
<service android:name=".ClipboardMonitorService" />
Then in MainActivity class start the service in onCreate()
as following:
startService(new Intent(this, ClipboardMonitorService.class));
ClipboardMonitorService class:
package com.kushal.webtest;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.IBinder;
public class ClipboardMonitorService extends Service {
private ClipboardManager mClipboardManager;
@Override
public void onCreate() {
super.onCreate();
mClipboardManager =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
System.out.println("Service started running..");
}
@Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
String charSequence = mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
System.out.println("Copied Link : ====================" + charSequence);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("copiedLink", charSequence);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
};
}