我的广播接收器工作但只有在我的应用程序运行时... 当我关闭程序时,广播接收器将不再工作。
我的代码:
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
答案 0 :(得分:0)
BroadCastReceivers
生命周期才会生效。如果您关闭应用程序将无法正常工作。如果您希望在应用关闭时收到通知,请调查AlarmManagers
答案 1 :(得分:0)