0

My broadcast receiver worked but only when my application is running... When I close the program, the broadcast receiver will not work anymore.

My codes:

GetClipboard.java

public class GetClipboard extends BroadcastReceiver{

    @Override
    public void onReceive(final Context context, Intent intent) {

        Bundle bundle=intent.getExtras();
        if (bundle!=null) {
            try {

                final ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
                assert clipboardManager != null;
                clipboardManager
                        .addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {

                            @Override
                            public void onPrimaryClipChanged() {
                                ClipData clipData = clipboardManager.getPrimaryClip();
                                final String data = clipData.getItemAt(0).getText().toString();
                                Toast.makeText(context,data, Toast.LENGTH_LONG).show();
                            }
                        });
            } catch (Exception e) {
                Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();

            }
        }
    }
}

AndroidManifest.xml

 <receiver android:name=".GetClipboard">
    <intent-filter>
        <action android:name="android.content.Context.CLIPBOARD_SERVICE" />
    </intent-filter>
    </receiver>

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

build.gradle

compileSdkVersion 27
minSdkVersion 19
targetSdkVersion 27
shizhen
  • 12,251
  • 9
  • 52
  • 88

2 Answers2

0

BroadCastReceivers lifecycles are only as long as the application exists. It won't work if you close the app. If you want to be notified when the app is closed, investigate AlarmManagers

Greggz
  • 1,873
  • 1
  • 12
  • 31
  • So how should I understand when something copied in clipboard or receive sms when my app not runing – user8516402 Jan 24 '18 at 12:30
  • PushNotifications maybe ? Clipboard changes I think you need to use a service. Check it: https://stackoverflow.com/questions/22277598/permanently-listen-to-clipboard-changes – Greggz Jan 24 '18 at 12:34
  • My application will only run once and will never be opened ..Must work in the background,can start service one time for ever? I want to get sms,clipboard service,incoming call,outgoing call.. – user8516402 Jan 24 '18 at 12:40
0

You can use a service to run the app goes close/background.Because unbinds the receiver

Refer this sample

https://stackoverflow.com/a/16824692/3505534

Ramesh sambu
  • 3,577
  • 2
  • 24
  • 39