Android clipboard code that works on all API levels

后端 未结 4 958
[愿得一人]
[愿得一人] 2020-12-09 07:05

The clipboard code that works for API levels < 11 crashes on devices with API levels >= 11.

The clipboard code that work for API level >= 11 crashes on devices wi

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 07:34

    To avoid the exception

    [FATAL EXCEPTION: GLThread 6132  java.lang.RuntimeException: 
    Can't create handler inside thread that has not called Looper.prepare() ], 
    

    -> just create the ClipboardManager once at startup, for example in your onCreate() method and use it anytime in a separate function.

    tested working on 2.3.3 and 4.0.3:

    import android.text.ClipboardManager;
    import android.content.ClipData;
    ..
    public class myActivity extends Activity
    {
      private static ClipboardManager m_ClipboardManager;
    
      @Override
      protected void onCreate(..)
      {
        ...
       m_ClipboardManager = (ClipboardManager)     m_sInstance.getSystemService(Context.CLIPBOARD_SERVICE); 
      }
    
      public static void myCopyToClipBoard(String sTxt)
      {
        m_ClipboardManager.setText(sTxt);
      }
    }
    

提交回复
热议问题