Android开发Android技术知识Android知识

【置顶】Android代码收藏(持续更新)

2017-12-28  本文已影响88人  Arison

EditText设置点击事件

有些时候搜索一些商品 为了美观会跳转到另一个页面进行搜索 
所以需要支持edittext的点击事件,但是前提要让edittext失去焦点要不然会弹出软键盘
EditText seachEditText = (EditText) findViewById(R.id.my_chat_seach); 
seachEditText.setFocusable(false);//让EditText失去焦点,然后获取点击事件
seachEditText.setOnClickListener(this);

Bitmap转File

  public static File saveBitmapFile(Bitmap bitmap, String filepath) {
        File file = new File(filepath);//将要保存图片的路径      
         try {          
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));       
             bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);         
             bos.flush();       
             bos.close(); 
         } catch (IOException e) {      
             e.printStackTrace(); 
         }  
         return file;
   }

ListView判断是否滚到顶部或者底部

mListView.setOnScrollListener(new OnScrollListener() {  
@Override  
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
    if (firstVisibleItem == 0) {  
        View firstVisibleItemView = mListView.getChildAt(0);  
        if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {  
            Log.d("ListView", "##### 滚动到顶部 #####");  
        }  
    } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {  
        View lastVisibleItemView = mListView.getChildAt(mListView.getChildCount() - 1);  
        if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == mListView.getHeight()) {  
            Log.d("ListView", "##### 滚动到底部 ######");         
        }  
    }  
}  

@Override  
public void onScrollStateChanged(AbsListView view, int scrollState) {  
    //do nothing  
}  
  
});  

Android icon桌面图标更改无效的问题

 方案一:Android icon正确更改,删除多余旧icon,clean项目
 方案二:载app清除手机缓存,重启手机。
 方案三:手机切换主题样式。由A主题换成B主题,再换回A主题 

ListView滚动时itemview背景色变成黑色的解决方式

  android:scrollingCache="false"
  android:cacheColorHint="#00000000" 

判断APP是否被打开

    /**
     * 判断程序是否打开
     * @return
     */
    public static boolean isRunningInForeground() {
        boolean isActivityFound = false;
        ActivityManager activityManager = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> services = activityManager
                .getRunningTasks(1);
        if (services.get(0).topActivity.getPackageName().toString()
                .equalsIgnoreCase(MyApplication.getInstance().getPackageName().toString())) {
            isActivityFound = true;
        }
        return isActivityFound;
    }     

Android WebView 电话,邮件UIR链接处理

   webView.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtil.d(TAG,"转发url:"+url);
            if (url.startsWith(WebView.SCHEME_TEL) || url.startsWith("sms:") || url.startsWith(WebView.SCHEME_MAILTO)) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    mContext.startActivity(intent);
                } catch (ActivityNotFoundException ignored) {
                }
                return true;
            }
            webView.loadUrl(url);
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    });

Android WebView网页端内部登录Cookies保持

@SuppressWarnings("static-method")
public void setCookiesEnabled(final boolean enabled) {
    CookieManager.getInstance().setAcceptCookie(enabled);
}

 @SuppressLint("NewApi")
public void setThirdPartyCookiesEnabled(final boolean enabled) {
    if (Build.VERSION.SDK_INT >= 21) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, enabled);
    }else{
       CookieManager.getInstance().setAcceptCookie(enabled);
   }
}

Android WebView客户端登录传递Cookie给网页端

public void synCookies(Context context, String url) {
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.removeSessionCookie();//移除
    cookieManager.setCookie(url, cookies);
    CookieSyncManager.getInstance().sync();
}

浏览器URL链接打开本地APP,没有安装就调转下载界面。

Android

  <!-- 启动页面 -->
    <activity android:name=".ui.SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="cat.ereza.customactivityoncrash.RESTART" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            
            <data android:scheme="app"
                android:host="usoftchina.com">
            </data>
        </intent-filter>
    </activity>

网页端

  <html>
  <head>
  <meta charset="utf-8">
  <script type="text/javascript">
window.onload = function()//用window的onload事件,窗体加载完毕的时候
{
    if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
        window.location.href = "com.baidu.tieba://";//ios url打开地址
        window
                .setTimeout(
                        function() {
                            window.location.href = "https://itunes.apple.com/cn/app/id477927812";//ios下载地址
                        }, 1000)
    } else if (navigator.userAgent.match(/android/i)) {

        window.location = "app://usoftchina.com";//android url打开地址
        window
                .setTimeout(
                        function() {
                            window.location.href = "http://shouji.baidu.com/software/23017307.html";//android 下载地址
                        }, 1000)
    }

}
  </script>
  </head>
  <body>
<!-- 测试打开移动APP -->
<!-- <a href="app://test0812">打开UU互联![测试网页链接打开移动APP] 测试成功! window.location</a> -->
   </body>
   </html>

注意:如果是从一个APP打开另外一个APP:

Uri uri = Uri.parse("app://usoftchina.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);//如果不存在app://usoftchina.com  会产生异常,需处理

浏览器URL链接打开本地APP,调转指定界面传递参数

Android端-接收参数

public class IntentUrlActivity extends Activity {
  private static final String TAG = "IntentUrlActivity";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_intent_url);
      Intent i_getvalue = getIntent();
      String action = i_getvalue.getAction();
      if(Intent.ACTION_VIEW.equals(action)){
               Uri uri = i_getvalue.getData();
               if(uri != null){
                    String pagekind = uri.getQueryParameter("pagekind");
                   String id= uri.getQueryParameter("id");
                    LogUtil.d(TAG,"pagekind:"+pagekind+" id:"+id);
                    if ("A".equals(pagekind)){
                            Intent intent=new Intent(this, SimpleWebActivity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("url","https://www.baidu.com");
                            intent.putExtra("p","询价单");
                            startActivity(intent);
                            
                     }
                   if ("B".equals(pagekind)){
                            Intent intent=new Intent(this, SimpleWebActivity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("url","https://github.com");
                            intent.putExtra("p","公共询价单");
                            startActivity(intent);
                          
                        }
                    if ("C".equals(pagekind)){
                            Intent intent=new Intent(this, SimpleWebActivity.class);
                            intent.putExtra("id",id);  
                          intent.putExtra("url","https://www.jianshu.com/u/7cfc7246c714");
                            intent.putExtra("p","采购单");
                            startActivity(intent);
                        }
                        overridePendingTransition(0,0);
                        finish();
                    }
                }
            }
        }

清单文件配置:

<activity android:name=".IntentUrlActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            <data android:scheme="app"
                android:host="usoftchina.com">
            </data>
        </intent-filter>
 </activity>

网页端-传递参数

<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
    window.onload = function()//用window的onload事件,窗体加载完毕的时候
    {
        var params=window.location.href;
        //window.alert(params.split("?")[1]);
        //document.write(params.split("?")[1]);
        if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
            window.location.href = "com.baidu.tieba://"+params.split("?")[1];//ios url打开地址
            window
                    .setTimeout(
                            function() {
                                window.location.href = "https://itunes.apple.com/cn/app/id477927812";//ios下载地址
                            }, 1000)
        } else if (navigator.userAgent.match(/android/i)) {

            window.location.href = "app://usoftchina.com?"+params.split("?")[1];//android url打开地址
            window
                    .setTimeout(
                            function() {
                                window.location.href = "http://shouji.baidu.com/software/23017307.html";//android 下载地址
                            }, 1000)
        }

    }
</script>
</head>
<body>
    <!-- 测试打开移动APP -->
    <!-- <a href="app://test0812">打开UU互联![测试网页链接打开移动APP] 测试成功! window.location</a> -->
</body>
</html>

WebView返回处理

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
    mWebView.goBack();// 返回前一个页面
     return true;
  }
  return super.onKeyDown(keyCode, event);
}

TextView设置和隐藏Drawableleft

image
上一篇 下一篇

猜你喜欢

热点阅读