Bài viết nhằm mục đích hiểu về gọi đến 1 service theo con đường gọi phương thức bindService() trong lập trình Android.
Mục tiêu : Tạo 1 service có chức năng tính toán và trả về kết quả của phương thức cộng 2 số nguyên.
Màn hình chương trình khi gọi phương thức cong2so(5,5) từ 1 service như sau :
Hàm onCreate(bundle) : nhận các đối tượng về từ giao diện :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
Trước hết, tạo 1 lớp có tên là MyService mở rộng từ lớp Service như sau :
public class MyService extends Service {
// Binder cho cac client
private final IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
//phương thức cho các client có thể gọi.
public int cong2So(int a, int b){
return a + b ;
}
public class LocalBinder extends Binder {
// Trả về đối tượng MyService để cho client có thể gọi public method
MyService getService(){
return MyService.this;
}
}
}
Trở lại Activity chính của ứng dụng :
Trong hàm OnStart() chúng ta dùng phương thức bindService(parameter) để gọi đến MyService thông qua đối tượng Intent .
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// Bind to MyService
Intent i = new Intent(this, MyService.class);
bindService(i, mConnection, Context.BIND_AUTO_CREATE)
}
Trong hàm onStop() : Ngắt kết nối đến MyService
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//Unbind from Service
if(mBound){
mService.unbindService(mConnection);
mBound = false ;
}
}
Tạo 1 biến mConnection từ lớp ServiceConnection nhằm Overide 2 phương thức sau nhằm bound đến MyService.
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Bound to MyService.
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
};;;
Cuối cùng trong phương thức onClick của button ta gọi đến hàm cong2so(int,int) và hiển thị kết quả của phương thức ra 1 textview như sau :
@Override
public void onClick(View v) {
if(v.getId() == R.id.button){
if(mBound){
int result = mService.cong2So(5, 5);
tv.setText(new String().valueOf(result));
}
}
}
Trong Android manifesh.xml thêm dòng này : <service android:name="MyService"></service> trong thẻ <application>
file 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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Hiển thị các bài đăng có nhãn android. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn android. Hiển thị tất cả bài đăng
25 thg 5, 2012
23 thg 5, 2012
Souce code client server trên Android qua tcp socket programing
Mục tiêu :
- Demo cách thức hoạt động của client server qua giao thức TCP.
- Gửi nhận dữ liệu giữa Server và Client.
- Xây dựng các ứng dụng client/server trên các thiết bị chạy android độc lập, không phụ thuộc vào pc.
Ý tưởng :
- Gửi dữ liệu từ client lên server.
- Hiển thị dữ liệu ra editText.
- Thông báo toast notification khi dữ liệu được gửi đến.
Cần biết :
- Socket và SocketServer.
- Toast Notification.
- Telnet Client.
Code :
- Cài đặt dịch vụ telnet client trên máy tính.
- Khởi động 2 máy ảo emulator.
- Vào cdm gõ lệnh sau : telnet localhost 5554 .
- Tiếp tục gõ lệnh : redir add tcp:9999:999 để cấu hình ánh xạ port giữa local port và server port cho máy ảo 5554 qua port 9999.
Làm đúng sẽ có hình như sau :
- Demo cách thức hoạt động của client server qua giao thức TCP.
- Gửi nhận dữ liệu giữa Server và Client.
- Xây dựng các ứng dụng client/server trên các thiết bị chạy android độc lập, không phụ thuộc vào pc.
Ý tưởng :
- Gửi dữ liệu từ client lên server.
- Hiển thị dữ liệu ra editText.
- Thông báo toast notification khi dữ liệu được gửi đến.
Cần biết :
- Socket và SocketServer.
- Toast Notification.
- Telnet Client.
Code :
- Cài đặt dịch vụ telnet client trên máy tính.
- Khởi động 2 máy ảo emulator.
- Vào cdm gõ lệnh sau : telnet localhost 5554 .
- Tiếp tục gõ lệnh : redir add tcp:9999:999 để cấu hình ánh xạ port giữa local port và server port cho máy ảo 5554 qua port 9999.
Làm đúng sẽ có hình như sau :
Bây giờ chúng ta chạy ứng dụng server trên máy ảo 5554, client trên máy ảo 5556.
Kết nối giữa client và server qua port 9999 và ip : 10.0.2.2 .
Kết nối giữa client và server qua port 9999 và ip : 10.0.2.2 .
Thực hiện đúng chúng ta sẽ có hình minh họa sau :
Bên trái là server, bên phải là client. Chú ý các phần được bôi khung vàng. Chúc vui.
14 thg 5, 2012
Một số phương thức vẽ các hình thông dụng
Khi nhấp vào các button thì ứng dụng sẽ vẽ các hình trên các View.
Thứ tự như sau :
Source code ứng dụng : http://and-sungha-blog.googlecode.com/files/Draw.rar
Multi Choice ListView
Cách sử dụng ListView với nhiều sự lựa chọn. Sử dụng với layout ListView đã được hỗ trợ sẵn.
Các bạn hoàn toàn có thể custom lại ListView với nhiều sự lựa chọn tùy vào ngữ cảnh của ứng dụng.
Dễ dàng nhất là chúng ta sử dụng các tài nguyên đã được xây dựng sẵn.
Code :
public class MutilChoiseListViewActivity extends Activity {
private ListView choiceLV;
private String[] choice = { "String A", "String B", "String C", "String D" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
choiceLV = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, choice);
choiceLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
choiceLV.setAdapter(adapter);
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Các bạn hoàn toàn có thể custom lại ListView với nhiều sự lựa chọn tùy vào ngữ cảnh của ứng dụng.
Dễ dàng nhất là chúng ta sử dụng các tài nguyên đã được xây dựng sẵn.
Code :
public class MutilChoiseListViewActivity extends Activity {
private ListView choiceLV;
private String[] choice = { "String A", "String B", "String C", "String D" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
choiceLV = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, choice);
choiceLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
choiceLV.setAdapter(adapter);
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
31 thg 3, 2012
Phương thức lấy CSDL SQL SERVER thông qua Web Service
//Phương thức lấy tên thành phố theo mã thành phố được truyền vào.
public static Model.City GetCityIdOfNameCity(string cityId)
{
try
{
conn = new SqlConnection(cs);
string sql = "SELECT cityName FROM city WHERE cityId = '" + cityId + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
reader = cmd.ExecuteReader();
reader.Read();
Model.City city = new Model.City();
// city.CityID = reader["cityId"].ToString();
city.CityName = reader["cityName"].ToString();
// city.CityDescript = reader["cityDescription"].ToString();
return city;
}
catch (Exception exp)
{
//Adding logging
HttpContext.Current.Trace.Warn("Error", "Error in GetCityIdOfNameCity", exp);
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
//Phương thức lấy tất cả tên thành phố trong bảng "city"
// Kết quả trả về là 1 List
public static List<string> GetAllCity()
{
try
{
conn = new SqlConnection(cs);
string sql = "SELECT cityName FROM city";
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
reader = command.ExecuteReader();
List<string> _allCity = new List<string>();
while (reader.Read())
{
_allCity.Add(reader.GetString(0));
}
return _allCity;
}
catch (Exception)
{
HttpContext.Current.Trace.Warn("Error", "Error at GetAllCity !!!!");
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
//Phương thức lấy tất cả tên ngân hàng trong bảng "bank"
// Kết quả trả về là 1 List
public static List<string> GetAllBank()
{
try
{
conn = new SqlConnection(cs);
string sql = "SELECT bankName FROM bank";
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
reader = command.ExecuteReader();
List<string> _allBank = new List<string>();
while (reader.Read())
{
_allBank.Add(reader.GetString(0));
}
return _allBank;
}
catch (Exception)
{
HttpContext.Current.Trace.Warn("Error", "Error at GetAllBank !!!!");
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
//Lấy các quận theo tên mã thành phố truyền vào
public static List<string> GetDistrictOfCity(string cityId){
try
{
conn = new SqlConnection(cs);
string sql = "SELECT distrctName FROM district WHERE cityId = '" + cityId + "' ";
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
reader = command.ExecuteReader();
List<string> _allDist = new List<string>();
while (reader.Read())
{
_allDist.Add(reader.GetString(0));
}
return _allDist;
}
catch (Exception)
{
HttpContext.Current.Trace.Warn("Error", "Error at GetDistrict !!!!");
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
//Lấy các cây atm theo ngân hàng và quận trong thành phố
public static List<string> getAtms(string bankId, string districtId)
{
try
{
conn = new SqlConnection(cs);
string sql = "SELECT atmName FROM atm WHERE districtId = '" + districtId + "' AND bankId = '" + bankId + "'";
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
reader = command.ExecuteReader();
List<string> _allAtms = new List<string>();
while (reader.Read())
{
_allAtms.Add(reader.GetString(0));
}
return _allAtms;
}
catch (Exception)
{
HttpContext.Current.Trace.Warn("Error", "Error at GetDistrict !!!!");
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
database download tại đây : http://code.google.com/p/and-project-lbd/downloads/detail?name=data.rar&can=2&q=#makechanges
21 thg 3, 2012
Lấy Latitude, Longitude trên Emulator của Android
Khi bạn làm việc về Location & Maps trong android. Khi bạn muốn lấy vị trí GPS Location hiện tại của thiết bị. Trên Emulator sẽ không có điều này, Emulator chỉ hỗ trợ chúng ta có thể thay đổi được vị trí Latitude và Longitude giúp chúng ta có thể dễ dàng kiểm tra.
Để sử dụng ta có thể làm theo 2 cách sau :
Lưu ý : Mở 1 emulator rồi mới thực hiện nhé.
Cách 1: Dùng tools trong Android SDK hỗ trợ chúng ta.
- Mở màn hình dos lên. Start -> gõ cmd.
- Các bạn chuyển đường dẫn đến thư mục tools nằm trong android sdk.
VD : D:\Eclipse\android-sdk-windows\tools\ (Thư mục do tôi để ở ổ D).
(Nhớ sử dụng phím tab khi làm việc trong cửa sổ Dos nhé).
- Chạy lệnh ddms.bat sẽ giúp bạn hiện được cửa sổ này lên. Đó chính là Dalvik Debug Monitor.
Để sử dụng ta có thể làm theo 2 cách sau :
Lưu ý : Mở 1 emulator rồi mới thực hiện nhé.
Cách 1: Dùng tools trong Android SDK hỗ trợ chúng ta.
- Mở màn hình dos lên. Start -> gõ cmd.
- Các bạn chuyển đường dẫn đến thư mục tools nằm trong android sdk.
VD : D:\Eclipse\android-sdk-windows\tools\ (Thư mục do tôi để ở ổ D).
(Nhớ sử dụng phím tab khi làm việc trong cửa sổ Dos nhé).
- Chạy lệnh ddms.bat sẽ giúp bạn hiện được cửa sổ này lên. Đó chính là Dalvik Debug Monitor.
Các bạn chú ý trong tab Emulator Control có mục Location Controls. Đó chính là mở bạn có thể thay đổi thông số GPS Location của Emulator.
Cách 2 : Với các bạn đã dùng Eclipse quen để lập trình trên Android OS, thì các bạn có thể bắt gặp của sổ này ở đâu đó. Cách này rất tiện lợi.
Các bạn chọn DDMS perspective trên góc phải của IDE. Eclipse sẽ chuyển qua 1 cửa sổ khác. và cũng có mục Emulator controls có chúng ta sử dụng.
Hi vọng giúp các bạn phần nào. Thân mến.
14 thg 3, 2012
[Networking Tut] Làm việc với networking sử dụng Thread và AsyncTask
Làm việc trên môi trường network với Thread và AsyncTask giúp cho ứng dụng xử lý tốt hơn trong khi đang load data về từ internet.
Các bạn kham khảo các vấn đề cần quan tâm trong bài này là :
Thread in android , đối tượng Handler, và lớp AsyncTask . và cách thức làm việc của các lớp này.
Hoàn thành bài này sẽ có kết quả như sau :
Các bạn kham khảo các vấn đề cần quan tâm trong bài này là :
Thread in android , đối tượng Handler, và lớp AsyncTask . và cách thức làm việc của các lớp này.
Hoàn thành bài này sẽ có kết quả như sau :
Class StringLoaderTask lấy data kiểu String extends từ lớp AsyncTask như sau :
private class StringLoaderTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
String result = null;
if (params.length <= 0) {
return null;
}
for (int i = 0; i < params.length; i++) {
String aURL = params[i];
try {
HttpClient httpclient = (HttpClient) new DefaultHttpClient();
HttpGet getobj = new HttpGet(aURL);
HttpResponse response = httpclient.execute(getobj);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity anEntity = response.getEntity();
Header aHeader = anEntity.getContentType();
if (aHeader.getValue().contains("text/")) {
result = EntityUtils.toString(anEntity);
}
}
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "Falied at ClientProtocolException with error: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, "Falied at IOException with error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, "Falied at Exception with error: " + e.getMessage());
e.printStackTrace();
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
if (result != null && result.length() > 0) {
mOutputContent.setText(result);
}
}
}
Class BitmapLoaderTask lấy data kiểu Bitmap extends từ lớp AsyncTask như sau :
private class BitmapLoaderTask extends AsyncTask<String, Integer, Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
Bitmap result = null;
if (params.length <= 0) {
return null;
}
for (int i = 0; i < params.length; i++) {
String aURL = params[i];
try {
HttpClient httpclient = (HttpClient) new DefaultHttpClient();
HttpGet getobj = new HttpGet(aURL);
HttpResponse response;
response = httpclient.execute(getobj);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity anEntity = response.getEntity();
Header aHeader = anEntity.getContentType();
if (aHeader.getValue().contains("image/")) {
result = new BitmapDrawable(anEntity.getContent()).getBitmap();
}
}
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "Falied at ClientProtocolException with error: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, "Falied at IOException with error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, "Falied at Exception with error: " + e.getMessage());
e.printStackTrace();
}
}
return result;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
mImageView.setImageBitmap(result);
}
}
}
Link download project : tại đây
[Networking Tut] Làm việc với networking trong Android
Bài này mình sẽ hướng dẫn các bạn thao tác với networking cơ bản
nhất.
Khi làm việc với
môi trường networking trên android, có 1 điều bạn luôn phải nhớ là cấp quyền
truy cập Internet cho ứng dụng của bạn. bằng cách vào trong file AndroidManifest.xml. Chọn thẻ Permision -> Chọn Add -> Uses Permision -> ở ô Name chọn quyền android.permission.INTERNET.
Ý tưởng : các bạn
sẽ lấy dữ liệu của 1 file xml trên môi trường mạng và hiển thị lên EditText. Và
dữ liệu 1 images và hiển thị lên 1 imageView.
File main.xml
trong thư mục res có dạng như sau :
<?xml version="1.0" encoding="utf-8"?>
<?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="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout
android:id="@+id/ll_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button2"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:layout_weight="0.29"
android:onClick="clickMe"
android:text="Load Image" />
<Button
android:id="@+id/button1"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_weight="0.34"
android:onClick="clickMe"
android:text="Connect" />
</LinearLayout>
<EditText
android:id="@+id/edtExt"
android:layout_width="match_parent"
android:layout_height="196dp" >
<requestFocus />
</EditText>
<ImageView
android:id="@+id/imgv"
android:layout_width="match_parent"
android:layout_height="220dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
Chúng ta tạo ra 1 phương thức để lấy dữ liệu theo dạng text như sau :
Với tham số truyển vào là 1 biến String chính là URL đến file xml.
Kết quả trả về cũng là 1 biến kiểu String.
public String getData(String urlStr) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlStr);
httpcon = (HttpURLConnection) url.openConnection();
int requestCode = httpcon.getResponseCode();
if(requestCode == HttpURLConnection.HTTP_OK){
InputStream is = httpcon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
result.append(line).append("\n");
}
br.close();
isr.close();
is.close();
}
httpcon.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
Phương thức lấy dữ liệu kiểu image.
Tham số là 1 biến kiểu String
Kết quả trả ra là 1 bitmap.
public Bitmap getImageData(String urlStr) {
try {
URI uri = new URI(urlStr);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse reponse = client.execute(get);
HttpEntity entity = reponse.getEntity();
InputStream is = entity.getContent();
bitmap = BitmapFactory.decodeStream(is);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
Hoàn thành project này các bạn lấy được thông tin như hình sau :
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout
android:id="@+id/ll_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button2"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:layout_weight="0.29"
android:onClick="clickMe"
android:text="Load Image" />
<Button
android:id="@+id/button1"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_weight="0.34"
android:onClick="clickMe"
android:text="Connect" />
</LinearLayout>
<EditText
android:id="@+id/edtExt"
android:layout_width="match_parent"
android:layout_height="196dp" >
<requestFocus />
</EditText>
<ImageView
android:id="@+id/imgv"
android:layout_width="match_parent"
android:layout_height="220dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
Chúng ta tạo ra 1 phương thức để lấy dữ liệu theo dạng text như sau :
Với tham số truyển vào là 1 biến String chính là URL đến file xml.
Kết quả trả về cũng là 1 biến kiểu String.
public String getData(String urlStr) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlStr);
httpcon = (HttpURLConnection) url.openConnection();
int requestCode = httpcon.getResponseCode();
if(requestCode == HttpURLConnection.HTTP_OK){
InputStream is = httpcon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
result.append(line).append("\n");
}
br.close();
isr.close();
is.close();
}
httpcon.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
Phương thức lấy dữ liệu kiểu image.
Tham số là 1 biến kiểu String
Kết quả trả ra là 1 bitmap.
public Bitmap getImageData(String urlStr) {
try {
URI uri = new URI(urlStr);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse reponse = client.execute(get);
HttpEntity entity = reponse.getEntity();
InputStream is = entity.getContent();
bitmap = BitmapFactory.decodeStream(is);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
Hoàn thành project này các bạn lấy được thông tin như hình sau :
Chúc vui. thân mến.
Vậy khuyết điểm của phương pháp này là gì ? Đó là khi đang trong quá trình load dữ liệu về. các control của giao diện màn hình sẽ bị đứng, ko xử lý nhạy được.Chính vì vậy thông thường người ta sẽ dùng Thread để truy xuất. Bài sau mình sẽ làm demo về Thread làm việc trên môi trường networking.
Download Project này tại đây .
[Source code] App tạo bàn phím ảo trên android
Bài này của 1 bạn có nick name là Kill ở 1 diễn đàn viết. Sợ quên nên mình copy về blog đọc sau vậy. Bài viết khá là hay và công sức của bạn ấy.
Ý tưởng : tạo ra 1 bàn phím có chức năng đơn giản như hình sau :
Bạn cần copy những resource cần thiết vào project của bạn làm
copy từ \android\platforms\<platform> vào thư mục \data\res\ (Nếu khó tìm bạn có thể download project của mình dưới bài viết)
Trong file layout của bạn, bạn cần add keyboard vào: /res/layout/main.xml
Tạo một file define cho bàn phím: /res/xml/qwerty.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
/**
*
* Copyright 2008, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="10%p"
android:horizontalGap="0px"
android:verticalGap="0px">
<Row>
<Key android:codes="113" android:keyLabel="q" android:keyEdgeFlags="left"/>
<Key android:codes="119" android:keyLabel="w"/>
<Key android:codes="101" android:keyLabel="e"/>
<Key android:codes="114" android:keyLabel="r"/>
<Key android:codes="116" android:keyLabel="t"/>
<Key android:codes="121" android:keyLabel="y"/>
<Key android:codes="117" android:keyLabel="u"/>
<Key android:codes="105" android:keyLabel="i"/>
<Key android:codes="111" android:keyLabel="o"/>
<Key android:codes="112" android:keyLabel="p" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="97" android:keyLabel="a" android:horizontalGap="5%p"
android:keyEdgeFlags="left"/>
<Key android:codes="115" android:keyLabel="s"/>
<Key android:codes="100" android:keyLabel="d"/>
<Key android:codes="102" android:keyLabel="f"/>
<Key android:codes="103" android:keyLabel="g"/>
<Key android:codes="104" android:keyLabel="h"/>
<Key android:codes="106" android:keyLabel="j"/>
<Key android:codes="107" android:keyLabel="k"/>
<Key android:codes="108" android:keyLabel="l" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="-1" android:keyIcon="@drawable/sym_keyboard_shift"
android:keyWidth="15%p" android:isModifier="true"
android:isSticky="true" android:keyEdgeFlags="left"/>
<Key android:codes="122" android:keyLabel="z"/>
<Key android:codes="120" android:keyLabel="x"/>
<Key android:codes="99" android:keyLabel="c"/>
<Key android:codes="118" android:keyLabel="v"/>
<Key android:codes="98" android:keyLabel="b"/>
<Key android:codes="110" android:keyLabel="n"/>
<Key android:codes="109" android:keyLabel="m"/>
<Key android:codes="-5" android:keyIcon="@drawable/sym_keyboard_delete"
android:keyWidth="15%p" android:keyEdgeFlags="right"
android:isRepeatable="true"/>
</Row>
<Row android:rowEdgeFlags="bottom">
<Key android:codes="-3" android:keyIcon="@drawable/sym_keyboard_done"
android:keyWidth="20%p" android:keyEdgeFlags="left"/>
<Key android:codes="-2" android:keyLabel="123" android:keyWidth="15%p"/>
<Key android:codes="32" android:keyIcon="@drawable/sym_keyboard_space"
android:keyWidth="30%p" android:isRepeatable="true"/>
<Key android:codes="46,44" android:keyLabel=". ,"
android:keyWidth="15%p"/>
<Key android:codes="10" android:keyIcon="@drawable/sym_keyboard_return"
android:keyWidth="20%p" android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
Trong lớp activity của bạn có thể dùng như sau:
package myApp.DemoKey;
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
public class DemoKey extends Activity implements OnKeyListener,
OnKeyboardActionListener {
private static final String TAG = DemoKey.class.getName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
KeyboardView keyboardView = (KeyboardView) findViewById(R.id.keyboardView);
Keyboard keyboard = new Keyboard(this, R.xml.qwerty);
keyboardView.setKeyboard(keyboard);
keyboardView.setEnabled(true);
keyboardView.setPreviewEnabled(true);
keyboardView.setOnKeyListener(this);
keyboardView.setOnKeyboardActionListener(this);
View button = findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
toggleKeyboardVisibility();
}
});
}
private void toggleKeyboardVisibility() {
KeyboardView keyboardView = (KeyboardView) findViewById(R.id.keyboardView);
int visibility = keyboardView.getVisibility();
switch (visibility) {
case View.VISIBLE:
keyboardView.setVisibility(View.INVISIBLE);
break;
case View.GONE:
case View.INVISIBLE:
keyboardView.setVisibility(View.VISIBLE);
break;
}
}
@Override
public void swipeUp() {
Log.d(TAG, "swipeUp");
}
@Override
public void swipeRight() {
Log.d(TAG, "swipeRight");
}
@Override
public void swipeLeft() {
Log.d(TAG, "swipeLeft");
}
@Override
public void swipeDown() {
Log.d(TAG, "swipeDown");
}
@Override
public void onText(CharSequence text) {
Log.d(TAG, "onText? \"" + text + "\"");
}
@Override
public void onRelease(int primaryCode) {
Log.d(TAG, "onRelease? primaryCode=" + primaryCode);
}
@Override
public void onPress(int primaryCode) {
Log.d(TAG, "onPress? primaryCode=" + primaryCode);
}
@Override
public void onKey(int primaryCode, int[] keyCodes) {
Log.d(TAG, "onKey? primaryCode=" + primaryCode);
int n1 = 0; // -1 count
for (int keyCode : keyCodes) {
if (keyCode == -1) {
n1++;
continue;
}
Log.v(TAG, "keyCode=" + keyCode);
}
Log.v(TAG, "keyCode=-1 *" + n1);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "onKey? keyCode=" + keyCode);
return false;
}
}
Bạn nào muốn demo thử thì tạo project rồi thử xem nhé. Khi nào mình có thời gian sẽ code hoàn thiện hơn rồi up link project lên tại đây.
13 thg 3, 2012
Touch Event của Android
Như chúng ta biết Touch Mode trong android cung cấp cho chúng ta 3 loai. Thứ nhất là tap(Chạm ngón tay vào màn hình), drag(chạm vào màn hình và giữ ngón tay 1 lúc và di chuyển), pintch-zoom(dùng 2 ngón tay zoom đối tượng nào đó).
Ở đây tôi sẽ giới thiệu cho bạn loại thứ 2 là sự kiện drag :
ý tưởng : vẽ 1 line từ vị trí chạm lần đầu đến vị trí cuối khi người sử dụng bỏ tay ra khỏi screen.
Dưới đây là code thực hiện :
package app.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class Test extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
float downx = 0, downy = 0, upx = 0, upy = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) this.findViewById(R.id.ImageView);
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
bitmap = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
imageView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
Chúc các bạn học tốt. Thân mến.
Ở đây tôi sẽ giới thiệu cho bạn loại thứ 2 là sự kiện drag :
ý tưởng : vẽ 1 line từ vị trí chạm lần đầu đến vị trí cuối khi người sử dụng bỏ tay ra khỏi screen.
Dưới đây là code thực hiện :
package app.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class Test extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
float downx = 0, downy = 0, upx = 0, upy = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) this.findViewById(R.id.ImageView);
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
bitmap = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
imageView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
Chúc các bạn học tốt. Thân mến.
Đăng ký:
Bài đăng (Atom)
Bản beta đầu tiên
Sau 6 tháng cả team cặm cụi làm việc điên cuồng, bản alpha cũng được giới thiệu ra toàn bộ công ty và được testing nội bộ công ty mà thôi. ...
-
Phần mềm đọc truyện tranh trên hệ điều hành android là 1 phần mềm cho phép hiển thị tuần tự các hình ảnh của 1 tập truyện được nén lại tron...
-
Đây là 1 bài viết vẽ đường đi giữa 2 tọa độ trên maps sử dụng kml file. Bài viết được lấy trên blog của 1 người TQ. Mình đang làm việc vớ...
-
Đang viết ứng dụng này. Mới xong được phần 1 của ứng dụng. Up thử lên youtube xem nào. :D Phần mềm giải quyết các điểm sau : - Kết nối đế...













