發表文章

目前顯示的是 2017的文章

android 背景執行方法 IntentService、Service

圖片
此方法建議不要長期使用timer長期執行,因為手機螢幕關閉後呈待機狀態timer會停止運作,用sleep(1000)也是會停止計時,想做長期定時通知請看我做定時通知 那篇 。 IntentService是Service的簡易版,已內建一個thread,如果只是想用一個thread就好這個非常適合,建立IntentService比建立Service簡單。 IntentService、Service我做的實驗目前情況: IntentService在完全關閉activity後會停止(就是關掉手機佔存在背景activity) Service在完全關閉activity後也會停止,但是能透過重新啟動service的方式重新啟動,可是service的程式就要重新執行一遍。 service 的生命週期 建立class方式 在manifest.xml裡會有 <service android:name=".MyService" android:enabled="true" android:exported="true" /> 在activity啟動service方式 //open intentservice Intent intent = new Intent(this, NotificationService.class); Log.d(TAG, "service start"); startService(intent); Service public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @

android 定時通知(永久長期的) 本篇只講AlarmManager使用

圖片
本篇使用AlarmManager達到準時執行某程式,跟鬧鐘的方式一樣,我之前用過IntentService、Service、Handler,都不能長期使用。 Servicer簡單缺點整理: IntentService:只要關閉activity背景保存視窗,IntentService背景所執行的程式就被強迫結束,好像可以重開(我沒試過)。 Service、Handler:雖然關閉activity會繼續執行,但他是重新在開啟一次service,這到還好,但當手機螢幕關閉處於待機狀態時,service會停止運作暫停在那邊,等你喚醒再繼續執行,所以用這個加timer做定時通知會整個亂掉,timer會停下來不數了。 AlarmManager主要架構是 跟系統註冊鬧鐘甚麼時間點 → 時間到系統會發送一個鬧鈴 → 你的activity接收那個鬧鈴後執行你的程式 當你註冊好幾個鬧鐘已經晚於現在時間,他會馬上通通都執行完 先建立接收鬧鈴的程式 在Manifest.xml 中加入接收系統鬧鈴 <application> <activity android:name=".MainActivity"> </activity> <!-- 當鬧鈴時間到達時要執行的程式 --> <receiver android:name=".AlarmReceiver"> <intent-filter> <action android:name="activity_app" /> </intent-filter> </receiver> </application> 建立一個class檔,執行接收到鬧鈴後的程式 public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {

android 手機螢幕翻轉 Activity 介面不更新

雖然用WebView可以顯示網頁,但是當手機翻轉後,他會重新再載入一次網頁,每翻轉一次就重新loading,使用者不舒服,service也會多負擔。 在 AndroidManifest.xml 加入 <manifest> <application> <activity ... android:name=".MainActivity" ... android:configchanges="orientation|keyboardhidden|screensize"> ↑ 加入這行 ↑ <intent-filter> <action android:name="android.intent.action.MAIN"/> </intent-filter> </activity > ... </application> </manifest> 從 Android 3.2 (API 13) 開始,螢幕翻轉螢幕尺寸也會跟著改變,所以要再加上 screenSize 在 Activity 中加入 @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { // 什麼都不用寫 } else { // 什麼都不用寫 } } 參考自: 官方: https://developer.androi

C# 系統音量調整由程式控制

public class demo { //運用WinAPI控制電腦靜音與音量 private const int APPCOMMAND_VOLUME_MUTE = 0x80000; private const int APPCOMMAND_VOLUME_UP = 0x0a0000; private const int APPCOMMAND_VOLUME_DOWN = 0x090000; private const int WM_APPCOMMAND = 0x319; //private static IntPtr Handle; public static Process p = Process.GetCurrentProcess(); [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); public static void btnVup_Click() { // 聲音變大 SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP); } public static void btnVdown_Click() { // 聲音變小 SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN); } public static void btnMute_Click() { // 靜音 SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); } /** * xp以下的電腦適用 * */

C# 模擬鍵盤滑鼠控制電腦

滑鼠模擬 指定一個螢幕像素的座標位置 int x = 1255; int y = 161; Cursor.Position = new Point(x, y); ClassMouse.LeftClick(); //按下滑鼠左鍵 鍵盤模擬 官方文件 的範例是用小算盤程式,計算111*11= public class demo { [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); // Activate an application window. [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd); // Send a series of key presses to the Calculator application. public static void Calculator() { // Get a handle to the Calculator application. The window class // and window name were obtained using the Spy++ tool. IntPtr calculatorHandle = FindWindow("ApplicationFrameWindow", "小算盤"); // Verify that Calculator is a running process. if (calculatorHandle == IntPtr.Zero) { MessageBox.Show("Calculator is not running.&q

第一次學習 C#

開啟外部程式 http://abgne.tw/code-snippets/dotnet-process.html 控制滑鼠 https://dotblogs.com.tw/sam319/2009/12/24/12643 加入cs (外部程式碼) https://social.msdn.microsoft.com/Forums/zh-TW/0b27dfdb-76e1-434a-ba64-80c972da82e2/c2cs?forum=233 invoke http://blog.xuite.net/merci0212/wretch/141175679-%5B%E8%BD%89%E8%BC%89%5DC%23+Invoke%E7%9A%84%E7%94%A8%E6%B3%95 https://dotblogs.com.tw/darrent/2010/12/02/19848 thread close http://www.programmer-club.com.tw/ShowSameTitleN/csharp/606.html https://dotblogs.com.tw/alexwang/2016/10/03/124332 c#  serial ports readline https://msdn.microsoft.com/zh-tw/library/system.io.ports.serialport.readline(v=vs.110).aspx get port to combobox http://catcsharp.blogspot.tw/2014/02/cwinform-rs-232serialport.html

raspberrypi 開機自動執行程式 與 在terminal開啟第二個terminal執行python

raspberrypi 開啟另一個terminal執行程式 在terminal輸入: lxterminal -e python3 demo.py 參考自: https://www.raspberrypi.org/forums/viewtopic.php?t=65607 ------------------------------------------------------------------------------------------------------------------------------------------------------- raspberrypi 開機自動執行程式 在terminal中輸入以下指令,開啟檔案: sudo nano /etc/rc.local 以下是加入執行python程式 #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. # Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then    printf "My IP address is %s\n" "$_IP" fi sudo python /home/pi/demo.py  <==加入在這邊 exit 0 參考自: http://dirtypig8.blogspot.tw/2016/12/python.html#!/tcmbck

python 匯出成exe 主要功能介紹

python 匯出成exe 安裝 pyinstaller python2.x:sudo pip install pyinstaller python3.x:sudo pip3 install pyinstaller 操作 基本:pyinstaller demo.py 他會在terminal目前目錄下建立兩個資料夾build 和 dist 建立執行檔在 dist 資料夾 其他細部功能看參考資料 參考自: http://zmh00.blogspot.tw/2016/01/python-codeexe.html http://zwindr.blogspot.tw/2016/01/python-pyinstaller.html

raspberry pi 3 上安裝 python的pyalsaaudio 來控制音量

圖片
目前我安裝pyalsaaudio的目的,是要用程式的方式控制rpi3上音量的大小 但在安裝過程中遇到一些瓶頸,因為我用的是python3,在這裡紀錄遇到的情形,及是如何解決的。 安裝 一開始輸入 sudo pip3 install pyalsaaudio 出現以下錯誤 pi@raspberrypi:~ $ sudo pip3 install pyalsaaudio Downloading/unpacking pyalsaaudio   Downloading pyalsaaudio-0.8.4.tar.gz (315kB): 315kB downloaded   Running setup.py (path:/tmp/pip-build-150927bh/pyalsaaudio/setup.py) egg_info for package pyalsaaudio         warning: no files found matching '*.json' under directory 'doc' Installing collected packages: pyalsaaudio   Running setup.py install for pyalsaaudio     building 'alsaaudio' extension     arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.4m -c alsaaudio.c -o build/temp.linux-armv7l-3.4/alsaaudio.o     alsaaudio.c:28:28: fatal error: alsa/asoundlib.h: 沒有此一檔案或目錄      #include                                 ^     compilation

python pyautogui 簡介

pyautogui 是 python的一個模組,他能控制鍵盤和滑鼠的操作,能利用它做自動化操作,像是用在軟體測試、重複性動作等。 pyautogui 暫停幾秒鐘 >>>pyautogui.PAUSE = 1.5 fail-safe (預設false) 當滑鼠一道螢幕左上角時,觸發 pyautogui 的failsafeexception 異常 >>>pyautogui.FAILSAFE = True 螢幕上的座標軸 (0,0) →→→→(1920,0)    ↓    ↓    ↓    ↓ (0,1080) 取得螢幕解析度 >>>import pyautogui >>>pyautogui.size() (1920, 1080) >>>width, height = pyautogui.size() 滑鼠部分 moveTo(width, height, duration) example移動到(300, 400)位置 pyautogui.moveTo(300, 400)                 #立即到 pyautogui.moveTo(300, 400, duration = 1.5) #花1.5秒移到 moeRel(width, height, duration) 移到相對座標,以當前滑鼠座標為基準點 pyautogui.moveRel(0, 100, duration=0.25) pyautogui.moveRel(-100, 0, duration=0.25) position() 獲得滑鼠當前的座標位置 >>>pyautogui.position() (300, 400) click(width, height, button) 滑鼠點擊 button = 'left', 'middle', 'right'。 pyautogui.click()                                #在當前位置點擊(預設左鍵) pyautogui.click(width, height)    

raspberry pi 3 安裝python pyautogui

圖片
主要安裝步驟 linux 需安裝其他的東西 sudo apt-get install python-tk sudo apt-get install python3-dev sudo apt-get install scrot sudo pip3 install python3-xlib 最後安裝 sudo pip3 install pyautogui 新版的應該是已安裝好以下: python-tk python3-dev scrot 錯誤一 如果直接安裝pyautogui會出現以下的錯誤 表示缺少xlib 只要安裝 python3-xlib完,再安裝pyautogui就可以了 錯誤二 如果像我其他都安裝好了,但是pyautogui還是安裝不成功,出現以下錯誤 那就把 sudo pip3 install pyautogui 改成 sudo xvfb-run pip3 install pyautogui 上網查 xvfb-run 應該是模擬安裝的意思 pi@raspberrypi:~ $ sudo pip3 install pyautogui Downloading/unpacking pyautogui Downloading PyAutoGUI-0.9.36.tar.gz (46kB): 46kB downloaded Running setup.py (path:/tmp/pip-build-0mnn6hrh/pyautogui/setup.py) egg_info for package pyautogui Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/Xlib/xauth.py", line 43, in __init__ raw = open(filename, 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: '/root/.Xauthority' During handling

空間活動偵測 -2 google app script

圖片
以Post的方式接收由pushingbox傳來的訊息,分別是磁簧開關5組,及人體紅外線6組 app script 接收端程式 function doPost(e) { var params = e.parameter; //現在時間 var now = Utilities.formatDate(new Date(), "GMT+8", "yyyy-MM-dd HH:mm:ss"); //編號1 的板子 if(params.board==1){ //*** 接收接點開關資料 ***// if(params.RS0){ Logger.log('接收接點開關資料'); //將Sheet指定為"資料庫"試算表 SpreadSheet = 試算表 var SpreadSheet = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //取得頁籤:"工作表1" Sheet = 頁籤 var Sheet = SpreadSheet.getSheetByName("board1 接點開關"); //取得有資料的最後一行的"行數"(目的要在最後一行插入新資料) var LastRow = Sheet.getLastRow(); //--開始寫入資料-- //在最後一行的下一行寫入資料 Sheet.getRange(LastRow+1, 1).setValue(now); //寫入time Sheet.getRange(LastRow+1, 2).setValue(params.time); //寫入data Sheet.getRange(LastRow+1, 3).setValue(params.RS0); //RS = Reed Switch 磁簧開

空間活動偵測 -1 arduino

圖片
我想做一個能夠及時通知家中發生異狀的系統 研究結果 用Arduino接收感測器資料,定時傳送資料人體紅外線資料,及即時傳送開關門資料,再用google apps script 做資料交換與分析,將arduino傳送過來的資料存入google試算表,由試算表做圖表繪製,再由apps script 定時推播圖表訊息,以及分析內容推播異常或警告訊息。 研究過程 一開始想用自己架設的伺服器存資料,用raspberry pi安裝apache + mysql + phpMyAdmin,但因為網路IP位置是浮動的關係,資料無法從外部傳回進伺服器,只能做本地端的資料傳輸,如果單使用arduino上傳資料到google試算表,又因為arduino uno3無網路連線加密的問題無法傳輸資料。 之後找到國外的伺服器能做資料交換,加上用google的試算表做簡單的資料庫儲存,所以最後是用arduino接收感測器資訊,傳輸到資料交換伺服器再到google,由apps script 接收資料及填入試算表,完成了資料接收的問題。 硬體:使用arduino uno3 + 乙太網路擴充板 + 自己做的電路板 連接的感測器: 人體紅外線感測器 門窗的磁簧開關 #include <Dhcp.h> #include <Dns.h> #include <Ethernet.h> #include <EthernetClient.h> #include <EthernetServer.h> #include <EthernetUdp.h> //#include "net_function.cpp" #include "set_ID.h" #define PushingBox unsigned char hour = 0, minute = 0; boolean push_man_check; String URL_data; #define ReedS0_pin 2 #define ReedS1_pin 3 #define ReedS2_pin 4 #define ReedS3_pin 5 #define ReedS4_pin 6 #define

python nn 聲音辨識 -2 建立nn

建立神經網路 網路上查聲音用這個function,跟這個loss算法(網站沒記下來) output_layer = add_layer(intput, input_tensors = input_len, output_tensors = output_len, n_layer = 1, activation_function = tf.nn.softmax) loss = tf.reduce_mean(-tf.reduce_sum(y_feeds * tf.log(output_layer), reduction_indices=[1])) 訓練與預測的函數很像 #訓練 要餵入 x , y sess.run(train, feed_dict = {x_feeds: x_data, y_feeds: y_data}) #放入loss 就能輸出現在loss值 loss_ = sess.run(loss, feed_dict={x_feeds: x_data, y_feeds: y_data}) #預測 只要餵入 x result = sess.run(output_layer, feed_dict = {x_feeds: [x_test]}) 完整程式碼: import tensorflow as tf import numpy as np import wav_fft as wavf import os # 定義一個添加層的函數 def add_layer(inputs, input_tensors, output_tensors, n_layer, activation_function = None): layer_name = 'layer%s' % n_layer print(layer_name) with tf.name_scope('Layer'): with tf.name_scope('Weights'): W = tf.Variable(tf.random_normal([input_tensors, output_tensors]), dtype=tf.float32 ,name = 'W')