FLAG_ACTIVITY_REORDER_TO_FRONT
例如Intent intent=new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.setClass(nowAtvity.this,targetActivity.class); startActivity(intent);
FLAG_ACTIVITY_REORDER_TO_FRONT
例如Intent intent=new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.setClass(nowAtvity.this,targetActivity.class); startActivity(intent);

TextView textView=(TextView)findViewById(R.id.txt); String str="您今天已經寫了100行書法"; //找到數字1的位置 int startIndex = str.indexOf('1'); //數字只有3個所以是startIndex+2 int endIndex = startIndex+2; //初始化Spannable Spannable textSpan = new SpannableStringBuilder(str); //將數字1之前的字串,字體大小設為28 像素 textSpan.setSpan(new AbsoluteSizeSpan(28), 0, startIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將數字100字體大小設為45 像素 textSpan.setSpan(new AbsoluteSizeSpan(45), startIndex, endIndex+1 , Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將100之後的內容字體大小設為28像素 textSpan.setSpan(new AbsoluteSizeSpan(28), endIndex+1 , str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將Spannable設定給TextView textView.setText(textSpan);
TextView textView=(TextView)findViewById(R.id.txt); String str="您今天已經寫了100行書法"; //找到數字1的位置 int startIndex = str.indexOf('1'); //數字只有3個所以是startIndex+2 int endIndex = startIndex+2; //初始化Spannable Spannable textSpan = new SpannableStringBuilder(str); //將數字1之前的字串,字體大小設為28 textSpan.setSpan(new AbsoluteSizeSpan(28,true), 0, startIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將數字100字體大小設為45 textSpan.setSpan(new AbsoluteSizeSpan(45,true), startIndex, endIndex+1 , Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將100之後的內容字體大小設為28 textSpan.setSpan(new AbsoluteSizeSpan(28,true), endIndex+1 , str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); //將Spannable設定給TextView textView.setText(textSpan);

| Non-0-length spans of type SPAN_INCLUSIVE_EXCLUSIVE expand to include text inserted at their starting point but not at their ending point. |
long lastTime=0 ; long now=0; public void myFun() { now=System.currentTimeMillis(); if (now-lastTime>500) { //do something lastTime=now; } }
long lastTime=0 ; long now=0; public void myFun() { now=System.currentTimeMillis(); if (Math.abs(now-lasttime)>500) { //do something last=now; } }
EditText it is always enabled, regardless of the value of the attribute.true" or "false".@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView=(TextView)findViewById(R.id.txt); Button button=(Button)findViewById(R.id.add); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int num=0; if (!textView.getText().toString().equals("")) { num=Integer.parseInt(textView.getText().toString()); } num++; textView.setText(String.valueOf(num)); } }); }


<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.boywhychen.context_menu.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/txt" android:freezesText="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/add" android:text="Add" android:layout_below="@+id/txt" /> </RelativeLayout>



String formatStr="%d + %d = %d"; TextView textView=(TextView)findViewById(R.id.txt); String text=String.format(formatStr,1,10,11); textView.setText(text);
String formatStr="%1$d + %3$d = %2$d"; TextView textView=(TextView)findViewById(R.id.txt); String text=String.format(formatStr,1,11,10); textView.setText(text);
GoogleApiClient. This reduces boilerplate and common pitfalls in your app.onConnected before making requests.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.boywhychen.context_menu.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/menu_btn" android:text="Context Menu" /> </RelativeLayout>

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/color_blue" android:title="Blue" android:orderInCategory="1" app:showAsAction="ifRoom"/> <item android:id="@+id/color_red" android:title="Red" android:orderInCategory="2" app:showAsAction="ifRoom"/> <item android:id="@+id/color_green" android:title="Green" android:orderInCategory="3" app:showAsAction="ifRoom"/> </menu>
package com.example.boywhychen.context_menu; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化Button Button menu_btn=(Button)findViewById(R.id.menu_btn); //幫Button註冊ContextMenu registerForContextMenu(menu_btn); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //要使用的Context Menu XML檔案 getMenuInflater().inflate(R.menu.my_menu,menu); } @Override public boolean onContextItemSelected(MenuItem item) { //按下Context Menu Item要做的事 switch ((item.getItemId())) { case R.id.color_blue: Toast.makeText(MainActivity.this,"Blue",Toast.LENGTH_SHORT).show(); break; case R.id.color_green: Toast.makeText(MainActivity.this,"Green",Toast.LENGTH_SHORT).show(); break; case R.id.color_red: Toast.makeText(MainActivity.this,"Red",Toast.LENGTH_SHORT).show(); break; } return super.onContextItemSelected(item); } }

socket.shutdownInput(); socket.shutdownOutput();
WifiConfiguration objects only if you created these objects. You are not permitted to modify or deleteWifiConfiguration objects created by the user or by other apps.enableNetwork() with the disableAllOthers=true setting, the device disconnected from other networks such as cellular data. In This release, the device no longer disconnects from such other networks. If your app’s targetSdkVersion is “20” or lower, it is pinned to the selected Wi-Fi network. If your app’s targetSdkVersion is “21” or higher, use the multinetwork APIs (such as openConnection(), bindSocket(), and the new bindProcessToNetwork() method) to ensure that its network traffic is sent on the selected network.openConnection(), bindSocket()或是bindProcessToNetwork() 方法。public boolean isPowerSaveMode() { PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && powerManager.isPowerSaveMode()) { return true; } else { return false; } }
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { //only catch need char (different with every one) char unicodeChar = (char) event.getUnicodeChar(); if (((keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_Z) || unicodeChar == '-') ) { isInput = true; unicodeChar = (char) event.getUnicodeChar(); sb.append(unicodeChar); //wait a delay time 500ms for read all data ( adjustment for your bar code scanner) if (isInput) { mHandler.postDelayed(new Runnable() { @Override public void run() { if (sb.length() != 0) { String str = sb.toString(); //save your String to UI Component isInput = false; } }, DELAY); } } return false; }
import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; public class MainActivity extends AppCompatActivity { /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("https://tw.yahoo.com"); } }
import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends Activity { WebViewClient mWebViewClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); mWebViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //process redirect URL view.loadUrl(url); return true; } }; //set WebviewClient to handle click hyper link , post... webView.setWebViewClient(mWebViewClient); webView.loadUrl("https://tw.yahoo.com"); } }
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
public void setCertificates(InputStream... certificates) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try { if (certificate != null) certificate.close(); } catch (IOException e) { } } SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init ( null, trustManagerFactory.getTrustManagers(), new SecureRandom() ); client.setSslSocketFactory(sslContext.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } }
//add self cert setCertificates(context.getResources().openRawResource(R.raw.nginx));
public MattermostService(Context context) { this.context = context; String userAgent = context.getResources().getString(R.string.app_user_agent); cookieStore = new WebkitCookieManagerProxy(); client.setCookieHandler(cookieStore); //add self cert setCertificates(context.getResources().openRawResource(R.raw.nginx)); preferences = context.getSharedPreferences("App", Context.MODE_PRIVATE); }
@Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // super.onReceivedSslError(view, handler, error);
handler.proceed(); }
protected void setWebViewClient(WebView view) { view.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { dialog.hide(); Log.i("onPageFinished", "onPageFinished while loading"); Log.i("onPageFinished", url); if (url.equals("about:blank")) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle(R.string.error_retry); alert.setPositiveButton(R.string.error_logout, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { MainActivity.this.onLogout(); } }); alert.setNegativeButton(R.string.error_refresh, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { MainActivity.this.loadRootView(); } }); alert.show(); } } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { Log.e("onReceivedHttpError", "onReceivedHttpError while loading"); StringBuilder total = new StringBuilder(); if (errorResponse.getData() != null) { BufferedReader r = new BufferedReader(new InputStreamReader(errorResponse.getData())); String line; try { while ((line = r.readLine()) != null) { total.append(line); } } catch (IOException e) { total.append("failed to read data"); } } else { total.append("no data"); } Log.e("onReceivedHttpError", total.toString()); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // super.onReceivedSslError(view, handler, error); handler.proceed(); } @Override public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) { Log.e("onReceivedErrord", "onReceivedError while loading (d)"); Log.e("onReceivedErrord", errorCode + " " + description + " " + failingUrl); webView.loadUrl("about:blank"); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); // Do not open in other browser if gitlab if (uri.getPath().contains("/oauth/authorize")) { return false; } // Do not open in other browser if gitlab if (uri.getPath().contains("/oauth/token")) { return false; } // Do not open in other browser if gitlab if (uri.getPath().contains("/api/v3/user")) { return false; } // Do not open in other browser if gitlab if (uri.getPath().contains("/users/sign_in")) { return false; } if (!uri.getHost().equalsIgnoreCase(appUri.getHost())) { openUrl(uri); return true; } if (uri.getPath().startsWith("/static/help")) { openUrl(uri); return true; } if (uri.getPath().contains("/files/get/")) { openUrl(uri); return true; } return super.shouldOverrideUrlLoading(view, url); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { // Check to see if we need to attach the device Id if (url.toLowerCase().contains("/channels/")) { if (!MattermostService.service.isAttached()) { Log.i("MainActivity", "Attempting to attach device id"); MattermostService.service.init(MattermostService.service.getBaseUrl()); Promise<User> p = MattermostService.service.attachDevice(); if (p != null) { p.then(new IResultListener<User>() { @Override public void onResult(Promise<User> promise) { if (promise.getError() != null) { Log.e("AttachDeviceId", promise.getError()); } else { Log.i("AttachDeviceId", "Attached device_id to session"); MattermostService.service.SetAttached(); } } }); } } } // Check if deviceID is missing if (url.toLowerCase().contains("/login")) { MattermostService.service.SetAttached(false); } // Check to see if the user was trying to logout if (url.toLowerCase().endsWith("/logout")) { MattermostApplication.handler.post(new Runnable() { @Override public void run() { onLogout(); } }); } return super.shouldInterceptRequest(view, url); } }); }