<小时/>
问题:无法从非 ui 后台线程设置剪贴板
<小时/>当我的应用程序在后台运行时,我该如何设置剪贴板?
public class Messages {
public void SetMessage(String text) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("NewClip", text);
clipboard.setPrimaryClip(clip);
}
}
}
错误:无法解析 getSystemService(java.lang.String)
<小时/>我尝试了多种方法来解决此问题,其中之一是:
<小时/>配置类
/* I made a Config class file like so: */
public final class Config {
public static com.dysanix.official.MainActivity MainContext = null;
}
/* And put this in the onCreate of the MainActivity: */
Config.MainContext = this;
/*
* And then using Config.MainContext.getSystemService() in the other
* class works, as long as the UI is visible on the screen.. but as soon as
* I tab out, the code doesn't work anymore.
*/
我还尝试在 MainActivity 中创建一个“Runnable”并从另一个类中调用它,但同样的问题:它有效,直到我退出应用程序。我从循环的 AsyncTask 调用该方法,我知道它是有效的,因为控制台在循环结束时不断打印日志消息。
任何帮助将不胜感激!
最佳答案
Error: Cannot resolve getSystemService(java.lang.String)
getSystemService()
是 Context
上的一个方法。将 Context
传递到您的 SetMessage()
方法中,或将该方法移至某些 Activity
、Service
或其他上下文
实现。然后,在该 Context
上调用 getSystemService()
。
I tried multiple things to solve this issue, one of them is:
不要将Activity
放入静态字段中。这不仅会导致内存泄漏,而且 Activity
一旦被销毁就毫无用处。
Issue: Can't set clipboard from non-ui background thread
这里没有任何与线程相关的内容。
关于java - 从非 ui 线程设置剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498939/