2015年5月24日 星期日

Android Notification LED Light Control LED燈 閃爍 控制

通知LED燈控制,測試有些手機可用,有些不可用,需在非充電下執行
1./res/layout/activity_main.xml


    

        

        
    



2.MainActivity.java
package tw.android;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 private NotificationManager notificationManager;
 private Notification notification;
 private boolean indeterminate = true; // true-開啟, false-關閉
 private int msInterval = 850; // 閃爍間隔時間(毫秒)

 private Button btStart, btStop;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  notification = new Notification();
  
  /* 啟用通知的led燈 */
  notification.flags = Notification.FLAG_SHOW_LIGHTS;
  /*notification閃亮間隔時間 */
  notification.ledOnMS=100; 
  notification.ledOffMS=100;

  btStart = (Button) findViewById(R.id.btStart);
  btStop = (Button) findViewById(R.id.btStop);

  /* 開始 */
  btStart.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    indeterminate = true;// 設為開啟
    new TwoColorBlink().execute(); // 執行LED燈閃爍

    btStart.setEnabled(false); // 開始按鈕-不可按
    btStop.setEnabled(true); // 關閉按鈕-可按

   }
  });

  /* 停止 */
  btStop.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {

    indeterminate = false;// 設為關閉
    notificationManager.cancel(0); // 關閉notificationManager

    btStart.setEnabled(true); // 開始按鈕-可按
    btStop.setEnabled(false); // 關閉按鈕-不可按
   }
  });

 }

 @Override
 protected void onPause() {
  indeterminate = false; // 設為關閉
  notificationManager.cancel(0); // 關閉notificationManager
  super.onPause();
 }

 private class TwoColorBlink extends AsyncTask<Void, Void, Void> {

  private int counter = 0; // 初始化次數

  @Override
  protected void onPreExecute() {

  }

  @Override
  protected Void doInBackground(Void... arg0) {
   try {

    synchronized (this) { //同一時間只有一個Thread執行
     
     notification.ledARGB = 0xFFFF0000;// 設定LED燈開始顏色

     while (indeterminate) { //重複閃爍

      notificationManager.notify(0, notification);//開啟notificationManager

      this.wait(msInterval); //閃爍間隔時間

      notificationManager.cancel(0); //關閉notificationManager

      if (counter++ % 2 == 0) {
       notification.ledARGB = 0xFF00FF00; //切換綠色
      } else {
       notification.ledARGB = 0xFF0000FF; //切換藍色
      }
      
     }

    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   

  }

 }

}

檔按下載:https://github.com/terryyamg/LedTest
參考來源:http://www.41post.com/4706/programming/android-creating-a-two-color-led-notification

2015年5月12日 星期二

Android Output Write File 輸出 寫入 文件

有時候字串太長,LogCat不好顯示,輸出文件是個好方法。
1.AndroidManifest.xml加入權限

2./res/layout/activity_main.xml


    
    

    


3.Write.java
package tw.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class Write {
 private static Context context;

 public Write(Context context) {
  this.context = context;
 }
 
 public static void WriteFileExample(String message) {
  FileOutputStream fop = null;
  File file;
  String content = message;

  try {
   File sdcard = Environment.getExternalStorageDirectory();
   file = new File(sdcard, context.getResources().getString(R.string.app_name)+"Log.txt"); //輸出檔案位置
   Log.i("Write File:", file + "");
   fop = new FileOutputStream(file);
   
   if (!file.exists()) { // 如果檔案不存在,建立檔案
    file.createNewFile();
   }

   byte[] contentInBytes = content.getBytes();// 取的字串內容bytes

   fop.write(contentInBytes); //輸出
   fop.flush();
   fop.close();

   Toast.makeText(context, "輸出完成", Toast.LENGTH_LONG).show();
   
  } catch (IOException e) {
   Log.i("Write E:", e + "");
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    Log.i("Write IOException", e + "");
    e.printStackTrace();
   }
  }
 }
}
4.MainActivity.java
package tw.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
 private EditText etWrite;
 private Button btWrite;
 private Write write = new Write(MainActivity.this);

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  etWrite = (EditText) findViewById(R.id.etWrite);
  btWrite = (Button) findViewById(R.id.btWrite);

  btWrite.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {

    write.WriteFileExample(etWrite.getText().toString()); // 寫入輸入文字
   }
  });

 }
}


檔案下載:
https://github.com/terryyamg/WriteFileTest
參考連結:
http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/

Android Get Phone WIFI IP 取得 網路 IP

取得手機或WIFI的IP位址
1.AndroidManifest.xml加入權限
    
    
    
2./res/layout/activity_main.xml


    

        
        

        
        
    

    

        
        

        
        
    

    

        
        

        
        
    

    

        
        

        
        
    


3.Utils.java
package tw.android;

import java.io.*;
import java.net.*;
import java.util.*;   
import org.apache.http.conn.util.InetAddressUtils;

public class Utils {

    /**
     * Convert byte array to hex string
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sbuf = new StringBuilder();
        for(int idx=0; idx < bytes.length; idx++) {
            int intVal = bytes[idx] & 0xff;
            if (intVal < 0x10) sbuf.append("0");
            sbuf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return sbuf.toString();
    }

    /**
     * Get utf8 byte array.
     * @param str
     * @return  array of NULL if error was found
     */
    public static byte[] getUTF8Bytes(String str) {
        try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
    }

    /**
     * Load UTF8withBOM or any ansi text file.
     * @param filename
     * @return  
     * @throws java.io.IOException
     */
    public static String loadFileAsString(String filename) throws java.io.IOException {
        final int BUFLEN=1024;
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
            byte[] bytes = new byte[BUFLEN];
            boolean isUTF8=false;
            int read,count=0;           
            while((read=is.read(bytes)) != -1) {
                if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
                    isUTF8=true;
                    baos.write(bytes, 3, read-3); // drop UTF8 bom marker
                } else {
                    baos.write(bytes, 0, read);
                }
                count+=read;
            }
            return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
        } finally {
            try{ is.close(); } catch(Exception ex){} 
        }
    }

    /**
     * Returns MAC address of the given interface name.
     * @param interfaceName eth0, wlan0 or NULL=use first interface 
     * @return  mac address or empty string
     */
    public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac==null) return "";
                StringBuilder buf = new StringBuilder();
                for (int idx=0; idx<mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));       
                if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                return buf.toString();
            }
        } catch (Exception ex) { } // for now eat exceptions
        return "";
        /*try {
            // this is so Linux hack
            return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
        } catch (IOException ex) {
            return null;
        }*/
    }

    /**
     * Get IP address from first non-localhost interface
     * @param ipv4  true=return ipv4, false=return ipv6
     * @return  address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                        if (useIPv4) {
                            if (isIPv4) 
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                return delim<0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) { } // for now eat exceptions
        return "";
    }

}

4.MainActivity.java
package tw.android;

import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;

public class MainActivity extends Activity {
 private TextView tvMac, tvWifi, tvIPV4, tvIPV6;

 /** Called when the activity is first created. */

 @SuppressWarnings("deprecation")
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  tvMac = (TextView) findViewById(R.id.tvMac);
  tvWifi = (TextView) findViewById(R.id.tvWifi);
  tvIPV4 = (TextView) findViewById(R.id.tvIPV4);
  tvIPV6 = (TextView) findViewById(R.id.tvIPV6);

  /* wifi ip位址 */
  WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
  String adWifi = Formatter.formatIpAddress(wm.getConnectionInfo()
    .getIpAddress());
  
  /* 手機網路ip位址 */
  String adMac = Utils.getMACAddress("wlan0");
  String ipv4 = Utils.getIPAddress(true); // IPv4
  String ipv6 = Utils.getIPAddress(true); // IPv6

  tvMac.setText(adMac);
  tvWifi.setText(adWifi);
  tvIPV4.setText(ipv4);
  tvIPV6.setText(ipv6);

 }
}

參考來源:
http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device

2015年5月11日 星期一

Android Internet Time 取得 網路 時間

Candy Crush APP就是抓取手機的時間,所以修改手機時間能獲得能量,有些APP則不能,因為抓取的為網路時間
1.AndroidManifest.xml加入網路權限
    
    
2.下載commons-net-3.1.jar
在專案建立libs資料夾,放至libs資料夾裡面

3./res/layout/activity_main.xml


    

        
        

        
        
    

    

        
        

        
        
    

    

    


4.MainActivity.java
package tw.android;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.time.TimeTCPClient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
 private TextView tvPhoneTime, tvInternetTime;
 private Button btUpdateTime, btChangeTime;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectDiskReads().detectDiskWrites().detectNetwork()
    .penaltyLog().build());
  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
    .build());

  tvPhoneTime = (TextView) findViewById(R.id.tvPhoneTime);
  tvInternetTime = (TextView) findViewById(R.id.tvInternetTime);
  btUpdateTime = (Button) findViewById(R.id.btUpdateTime);
  btChangeTime = (Button) findViewById(R.id.btChangeTime);

  /* 更新時間 */
  btUpdateTime.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    updateTime();
   }
  });

  /* 前往修改手機時間 */
  btChangeTime.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    Intent intent = new Intent(Settings.ACTION_DATE_SETTINGS);
    startActivity(intent);
   }
  });
 }

 @SuppressLint("SimpleDateFormat")
 private void updateTime() {
  /* 手機時間 */
  SimpleDateFormat sTime = new SimpleDateFormat("HH:mm:ss");
  String time = sTime.format(new java.util.Date()); // 現在時間
  tvPhoneTime.setText(time);

  /* 網路時間 */
  try {
   TimeTCPClient client = new TimeTCPClient();
   try {
    client.setDefaultTimeout(60000); // 設定最長等待時間為60秒
    /* 可以前往 http://tf.nist.gov/tf-cgi/servers.cgi 選擇可用的連結點 */
    client.connect("time-nw.nist.gov"); // 取得網路時間
    String iT = sTime.format(client.getDate());// 格式處理

    tvInternetTime.setText(iT);
   } finally {
    client.disconnect(); // 關掉連結
   }
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}

檔案下載:
 https://github.com/terryyamg/InternetTimeTest
參考連結:
http://stackoverflow.com/questions/13064750/how-to-get-current-time-from-internet-in-android
http://tf.nist.gov/tf-cgi/servers.cgi
http://grepcode.com/snapshot/repo1.maven.org/maven2/commons-net/commons-net/3.1