***********************************
test3.php
***********************************
<?php
?>
**********************************************************************
GetPhpServerMessageDemoActivity.java
**********************************************************************
public class GetPhpServerMessageDemoActivity extends Activity {
/** Called when the activity is first created. */
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.text_view);
String msg = stringQuery("http://localhost/androidapp/android_connect/test3.php");
textView.setText("Server message is "+msg);
}
public String stringQuery(String url){
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = httpclient.execute(method);
/*HttpEntity entity = response.getEntity();*/
if(response != null){
return response.getStatusLine().toString();
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
因為我們只要測試是否連線正常 回傳 200 為正常
只要有產生 php 的檔案就可以了!!
Android 4.0 ↑請看 :
Recognizer + Android 4.0↑ HttpClient 實作
2014年12月17日 星期三
Recognizer + Android 4.0↑ HttpClient 實作
***********************************
test3.php
***********************************
<?php
header ("Content-Type:text/html; charset=utf-8");
$response = $_POST['data'];
echo $response;
?>
***********************************
Main.java
***********************************
public class Main extends Activity implements OnClickListener
{
private String txtMessage;
private Button sendBtn;
private TextView tv;
private String uriAPI = "http://localhost/androidapp/test3.php";
protected static final int REFRESH_DATA = 0x00000001;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sendBtn = (Button) findViewById(R.id.send_btn);
tv = (TextView)findViewById(R.id.textView1);
if (sendBtn != null)
sendBtn.setOnClickListener(this);
}
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case REFRESH_DATA:
String result = null;
if (msg.obj instanceof String)
result = (String) msg.obj;
if (result != null)
tv.setText(result);
break;
}
}
};
@Override
public void onClick(View v)
{
if (v == sendBtn)
{
Intent it = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
it.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
it.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
this.startActivityForResult(it, 1);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent it) {
if (requestCode != 1) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtMessage = list.get(0);
this.onclick2(txtMessage);
}
public void onclick2 (String txtMessage) {
if (txtMessage != null)
{
final String msg = txtMessage.toString();
Thread t = new Thread(new sendPostRunnable(msg));
t.start();
}
}
class sendPostRunnable implements Runnable
{
String strTxt = null;
public sendPostRunnable(String strTxt)
{
this.strTxt = strTxt;
}
@Override
public void run()
{
String result = sendPostDataToInternet(strTxt);
mHandler.obtainMessage(REFRESH_DATA, result).sendToTarget();
}
}
private String sendPostDataToInternet(String strTxt)
{
HttpPost httpRequest = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", strTxt));
try
{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200)
{
String strResult = EntityUtils.toString(httpResponse
.getEntity());
return strResult;
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
***********************************
main.xml
***********************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/send" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
***********************************
AndroidManifest.xml
***********************************
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.J_Test.httpPostTest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 這裡加入可以存取網路的權限 -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Android 2.2 ↑↓請看:
android 2.2 ↑↓ 版使用 HtppClient
test3.php
***********************************
<?php
header ("Content-Type:text/html; charset=utf-8");
$response = $_POST['data'];
echo $response;
?>
***********************************
Main.java
***********************************
public class Main extends Activity implements OnClickListener
{
private String txtMessage;
private Button sendBtn;
private TextView tv;
private String uriAPI = "http://localhost/androidapp/test3.php";
protected static final int REFRESH_DATA = 0x00000001;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sendBtn = (Button) findViewById(R.id.send_btn);
tv = (TextView)findViewById(R.id.textView1);
if (sendBtn != null)
sendBtn.setOnClickListener(this);
}
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case REFRESH_DATA:
String result = null;
if (msg.obj instanceof String)
result = (String) msg.obj;
if (result != null)
tv.setText(result);
break;
}
}
};
@Override
public void onClick(View v)
{
if (v == sendBtn)
{
Intent it = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
it.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
it.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
this.startActivityForResult(it, 1);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent it) {
if (requestCode != 1) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtMessage = list.get(0);
this.onclick2(txtMessage);
}
public void onclick2 (String txtMessage) {
if (txtMessage != null)
{
final String msg = txtMessage.toString();
Thread t = new Thread(new sendPostRunnable(msg));
t.start();
}
}
class sendPostRunnable implements Runnable
{
String strTxt = null;
public sendPostRunnable(String strTxt)
{
this.strTxt = strTxt;
}
@Override
public void run()
{
String result = sendPostDataToInternet(strTxt);
mHandler.obtainMessage(REFRESH_DATA, result).sendToTarget();
}
}
private String sendPostDataToInternet(String strTxt)
{
HttpPost httpRequest = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", strTxt));
try
{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200)
{
String strResult = EntityUtils.toString(httpResponse
.getEntity());
return strResult;
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
***********************************
main.xml
***********************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/send" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
***********************************
AndroidManifest.xml
***********************************
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.J_Test.httpPostTest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 這裡加入可以存取網路的權限 -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Android 2.2 ↑↓請看:
android 2.2 ↑↓ 版使用 HtppClient
2014年12月4日 星期四
一個.java檔 完成呼叫google語音辨識系統
只要一個.java完成呼叫google語音辨識系統
這不是很方便嗎?
接下來我們就來看一下程式碼囉!!
/***********************************************
MainActivity.java
***********************************************/
public class MainActivity extends ActionBarActivity {
private ImageButton btnspeak; //在這裡我們就宣告一個 ImageButton 型態的 btnspeak變數
private static final String TAG = "SpeechRecognizerActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llbtn(); //在這裡我們呼叫llbtn這麼function
}
//viewbtn 這裡就是我們所呼叫的llbtn的function,接下來看一下做了什麼事情
public void llbtn() {
//這邊宣告ll 變數型態為LinearLayout
LinearLayout ll=(LinearLayout) findViewById(R.id.LinearLayout1);
//在這new ImageButton 出來
btnspeak =new ImageButton(this);
//設定ImageButton 的圖案為ic_btn_speak_now,如果要設定文字的話就要用Button型態宣告以及設定時使用setText()這個方法來作設定
btnspeak.setImageDrawable(getResources().getDrawable(drawable.ic_btn_speak_now));
//ll加入View出btnSpeak變數
ll.addView(btnspeak);
//設定 l 為btnspeak 呼叫的function
btnspeak.setOnClickListener(l);
}
//接下來就是呼叫語音辨識系統了
private ImageButton.OnClickListener l=new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
Intent it = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
it.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
it.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
//這裡要小心 在Android Recognizer文章中這裡是 "this.startActivityForResult(it,1);"這樣無法呼叫傳 (it ,1) 給onActivityResult這個function喔!!
startActivityForResult(it, 1);
}
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent it) {
if (requestCode != 1) {
Log.d(TAG, "不是語音辨識");
return;
}
if (resultCode != RESULT_OK) {
Log.e(TAG, "語音辨識失敗");
return;
}
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuilder text = new StringBuilder();
for (String s : list) {
text.append(s + "\n");
}
}
/**************************************************************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
這樣是不是簡單多了呢!!
2014年11月30日 星期日
Android App 控制返回鍵
因為返回件為大多數Android 手機必備的按鍵
在我昨天學到的三秒跳轉頁面發現這樣一個問題
按下回上一頁@@
怎麼跳回去上一個activity的頁面了!!
今天研究出了解決這樣的問題點
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
startActivity(new Intent().setClass(SplashActivity.this, MainActivity.class));
/*如果要在三秒後跳到主頁面後返回不要跳回此頁,可加入這行*/
xsystarActivity.this.finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
加上一點美感的返回對話框
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*返回建設定*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
ConfirmExit();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void ConfirmExit() {
// TODO Auto-generated method stub
AlertDialog.Builder ad=new AlertDialog.Builder(MainActivity.this); //創建訊息方塊
ad.setTitle("離開");
ad.setMessage("確定要離開?");
ad.setPositiveButton("是", new DialogInterface.OnClickListener() { //按"是",則退出應用程式
public void onClick(DialogInterface dialog, int i) {
MainActivity.this.finish();
}
});
ad.setNegativeButton("否",new DialogInterface.OnClickListener() { //按"否",則不執行任何操作
public void onClick(DialogInterface dialog, int i) {
}
});
ad.show();
}
在我昨天學到的三秒跳轉頁面發現這樣一個問題
按下回上一頁@@
怎麼跳回去上一個activity的頁面了!!
今天研究出了解決這樣的問題點
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
startActivity(new Intent().setClass(SplashActivity.this, MainActivity.class));
/*如果要在三秒後跳到主頁面後返回不要跳回此頁,可加入這行*/
xsystarActivity.this.finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
加上一點美感的返回對話框
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*返回建設定*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
ConfirmExit();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void ConfirmExit() {
// TODO Auto-generated method stub
AlertDialog.Builder ad=new AlertDialog.Builder(MainActivity.this); //創建訊息方塊
ad.setTitle("離開");
ad.setMessage("確定要離開?");
ad.setPositiveButton("是", new DialogInterface.OnClickListener() { //按"是",則退出應用程式
public void onClick(DialogInterface dialog, int i) {
MainActivity.this.finish();
}
});
ad.setNegativeButton("否",new DialogInterface.OnClickListener() { //按"否",則不執行任何操作
public void onClick(DialogInterface dialog, int i) {
}
});
ad.show();
}
Android App 進入程式前畫面
/************************************************************************
* MainActivity.java *
* *
************************************************************************/
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
/************************************************************************
* SplashActivity.java *
* 在src的資料夾裡建立此 .java 檔 *
************************************************************************/
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
startActivity(new Intent().setClass(SplashActivity.this, MainActivity.class));
/*如果要在三秒後跳到主頁面後返回不要跳回此頁,可加入這行*/
xsystarActivity.this.finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
/************************************************************************
* activity_main.xml *
* *
************************************************************************/
<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.test.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
/************************************************************************
* splash.xml *
* 自行在/res/layout資料夾下建立這個檔案 *
************************************************************************/
/************************************************************************
* AndroidManifest.xml *
* *
************************************************************************/
<activity
//這邊要注意一下喔!! 你建立專案的名稱
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
</activity>
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
* MainActivity.java *
* *
************************************************************************/
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
/************************************************************************
* SplashActivity.java *
* 在src的資料夾裡建立此 .java 檔 *
************************************************************************/
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
startActivity(new Intent().setClass(SplashActivity.this, MainActivity.class));
/*如果要在三秒後跳到主頁面後返回不要跳回此頁,可加入這行*/
xsystarActivity.this.finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
/************************************************************************
* activity_main.xml *
* *
************************************************************************/
<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.test.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
/************************************************************************
* splash.xml *
* 自行在/res/layout資料夾下建立這個檔案 *
************************************************************************/
<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=".MainActivity"
android:background="@drawable/darkgray" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@string/app_name"
android:src="@drawable/butterfly" />
</RelativeLayout>
/************************************************************************
* AndroidManifest.xml *
* *
************************************************************************/
<activity
//這邊要注意一下喔!! 你建立專案的名稱
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
</activity>
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
點入App的第一個畫面 |
3秒後跳轉至的頁面 |
2014年11月27日 星期四
語音文字判斷(比對)
最近在用語音出來的文字如何判斷
今天終於給我是出來了
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
/*這段再作判斷以及取得list取得第一個陣列文字作判斷就好了*/
if (list.get(0).equals("賽夏")) {
tv.setText("賽夏");
}else {
tv.setText("查無此意");
}
語音請參考這裡:http://kuoapp.blogspot.tw/2014/11/android.html
今天終於給我是出來了
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
/*這段再作判斷以及取得list取得第一個陣列文字作判斷就好了*/
if (list.get(0).equals("賽夏")) {
tv.setText("賽夏");
}else {
tv.setText("查無此意");
}
語音請參考這裡:http://kuoapp.blogspot.tw/2014/11/android.html
2014年11月26日 星期三
好玩的 Vibrate service
/**************************************************************
AndroidManifest.xml
**************************************************************/
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
/**************************************************************
MainActivity.java
**************************************************************/
public class MainActivity extends ActionBarActivity {
private Button btn_vibrate;
private Vibrator vibrate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_vibrate = (Button) findViewById(R.id.button1);
vibrate=(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btn_vibrate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibrate.vibrate(20000);
}
});
}
------------------------------------------------以下可省略-----------------------------------------------------
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
------------------------------------------------以上可省略-----------------------------------------------------
/**************************************************************
MainActivity.java
**************************************************************/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.service.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
AndroidManifest.xml
**************************************************************/
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
/**************************************************************
MainActivity.java
**************************************************************/
public class MainActivity extends ActionBarActivity {
private Button btn_vibrate;
private Vibrator vibrate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_vibrate = (Button) findViewById(R.id.button1);
vibrate=(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btn_vibrate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibrate.vibrate(20000);
}
});
}
------------------------------------------------以下可省略-----------------------------------------------------
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
------------------------------------------------以上可省略-----------------------------------------------------
/**************************************************************
MainActivity.java
**************************************************************/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.service.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
2014年11月18日 星期二
android app demotouch homework
MainActivity.java
package com.example.demotouch;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class MainActivity extends ActionBarActivity {
private LinearLayout ll;
private myview mv;
private Button btnBlack;
private Button btnBlue;
private Button btnred;
private Button btnclear;
private SeekBar sb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll=(LinearLayout) findViewById(R.id.LinearLayout1);
btnclear=new Button(this);
btnclear.setText("Clear");
ll.addView(btnclear);
btnclear.setOnClickListener(l);
sb = new SeekBar(this);
sb.setMax(50);
ll.addView(sb);
//black
btnBlack=new Button(this);
btnBlack.setText("black");
ll.addView(btnBlack);
//blue
btnBlue=new Button(this);
btnBlue.setText("blue");
ll.addView(btnBlue);
//red
btnred=new Button(this);
btnred.setText("red");
ll.addView(btnred);
mv=new myview(this);
ll.addView(mv);
btnBlack.setOnClickListener(l);
btnBlue.setOnClickListener(l);
btnred.setOnClickListener(l);
sb.setOnSeekBarChangeListener(sk);
}
private SeekBar.OnSeekBarChangeListener sk =new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
mv.w=progress;
mv.invalidate();
}
};
private Button.OnClickListener l=new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(((Button)v).getText().toString().equalsIgnoreCase("black")) mv.color=Color.BLACK;
else if(((Button)v).getText().toString().equalsIgnoreCase("blue")) mv.color=Color.BLUE;
else if(((Button)v).getText().toString().equalsIgnoreCase("red")) mv.color=Color.RED;
mv.invalidate();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
myview.java
package com.example.demotouch;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class MainActivity extends ActionBarActivity {
private LinearLayout ll;
private myview mv;
private Button btnBlack;
private Button btnBlue;
private Button btnred;
private Button btnclear;
private SeekBar sb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll=(LinearLayout) findViewById(R.id.LinearLayout1);
btnclear=new Button(this);
btnclear.setText("Clear");
ll.addView(btnclear);
btnclear.setOnClickListener(l);
sb = new SeekBar(this);
sb.setMax(50);
ll.addView(sb);
//black
btnBlack=new Button(this);
btnBlack.setText("black");
ll.addView(btnBlack);
//blue
btnBlue=new Button(this);
btnBlue.setText("blue");
ll.addView(btnBlue);
//red
btnred=new Button(this);
btnred.setText("red");
ll.addView(btnred);
mv=new myview(this);
ll.addView(mv);
btnBlack.setOnClickListener(l);
btnBlue.setOnClickListener(l);
btnred.setOnClickListener(l);
sb.setOnSeekBarChangeListener(sk);
}
private SeekBar.OnSeekBarChangeListener sk =new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
mv.w=progress;
mv.invalidate();
}
};
private Button.OnClickListener l=new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(((Button)v).getText().toString().equalsIgnoreCase("black")) mv.color=Color.BLACK;
else if(((Button)v).getText().toString().equalsIgnoreCase("blue")) mv.color=Color.BLUE;
else if(((Button)v).getText().toString().equalsIgnoreCase("red")) mv.color=Color.RED;
mv.invalidate();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
========================================================================
myview.java
package com.example.demotouch;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
public class myview extends View {
int color = Color.BLUE;
int w = 10;
private Path path = new Path();
private Paint paint = new Paint();
private PointF p;
public myview(Context context) {
super(context);
// TODO Auto-generated constructor stub
paint.setColor(color);
paint.setStyle(paint.getStyle().STROKE);
paint.setStrokeWidth(10);
paint.setAntiAlias(true);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
PointF p=new PointF();
p.x=event.getX();
p.y=event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(p.x, p.y);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(p.x, p.y);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(color);
paint.setStrokeWidth(w);
canvas.drawPath(path, paint);
super.onDraw(canvas);
}
}
========================================================================
2014年11月12日 星期三
Android Recognizer
範例程式碼
import........省略
public class MainActivity extends ActionBarActivity {
private static final String TAG = "SpeechRecognizerActivity";
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tv = (TextView) this.findViewById(R.id.tv);
}
public void onText(View v) {
Intent it = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
it.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
it.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
this.startActivityForResult(it, 1);
}
public void onWeb(View v) {
Intent it = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
it.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
it.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說...");
// 不用等結果
this.startActivity(it);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent it) {
if (requestCode != 1) {
Log.d(TAG, "不是語音辨識");
return;
}
if (resultCode != RESULT_OK) {
Log.e(TAG, "語音辨識失敗");
return;
}
List<String> list = it.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuilder text = new StringBuilder();
for (String s : list) {
text.append(s + "\n");
}
this.tv.setText(text);
}
//以下可省略
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
加入在:activity_main.xml
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onText"
android:text="語音辨識" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onWeb"
android:text="網頁搜尋" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"/>
</ScrollView>
標記黃色區塊加入在:AndroidManifest.xml
可加可不加 要觸發onWeb(View v)才需要網路
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.recognizer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
訂閱:
文章 (Atom)