2015年5月25日 星期一
【Android】App支援多種不同螢幕規格的方式
官方文件及網站找到的資料, 寫的很好, 但android 機型實在太多了, 有些要實機測一下, 才不會失真
http://magiclen.org/android-screen/
【Android】使用AsyncTask下載檔案
簡單運用, 記得改一些參數
private class downloadPost extends AsyncTask<String, Integer, String> {
private Context context;
private ProgressDialog pd;
private String strUrl;
public downloadPost(Context context, String url) {
this.context = context;
strUrl = url;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("下載中 ...");
pd.setCancelable(false);
pd.show();
}
@Override
protected String doInBackground(String... params) {
downloadFile(strUrl);
return null;
}
// run Progress
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (pv.DEBUG_MODE) System.out.println(TAG + "values:" + values[0]);
pd.setProgress(values[0]); // update Progress
}
// cancel upload
@Override
protected void onCancelled() {
if (pv.DEBUG_MODE) System.out.println(TAG + "onCancelled");
}
@Override
protected void onPostExecute(String result) {
if (pv.DEBUG_MODE) {
System.out.println("result onPostExecute : " + result);
}
player = new MusicPlayer(saveFileName, skbProgress);
pd.dismiss();
Toast.makeText(LessonContentActivity.this, "下載完成", Toast.LENGTH_SHORT).show();
}
private void downloadFile(String fileUrl) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(fileUrl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File(Environment.getExternalStorageDirectory() + "/easylisten/" + courseId + "/");
if (!SDCardRoot.exists()) {
SDCardRoot.mkdirs();
}
//create a new file, specifying the path, and the filename
//which we want to save the file as.
//file Name : i.am.a.file.jpg || hahaha
//fileUrl : http://solvefzt2.fzt.cc/.../i.am.a.file.jpg || hahaha.png
String realFileName = fileUrl.split("/")[fileUrl.split("/").length - 1];
String fileMime = realFileName.split("\\.")[realFileName.split("\\.").length - 1];
if (pv.DEBUG_MODE) {
System.out.println(TAG + "realFileName:" + realFileName);
System.out.println(TAG + "fileMime:" + fileMime);
}
File file = null;
file = new File(SDCardRoot, realFileName);
if (pv.DEBUG_MODE) {
System.out.println(TAG + "file.isFile SDCardRoot,realFileName:" + SDCardRoot + "/" + realFileName);
}
saveFileName = SDCardRoot + "/" + realFileName;
if (file.isFile()) {
return;
}
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the Progress
publishProgress((int) ((downloadedSize / totalSize) * 100));
fileOutput.flush();
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class downloadPost extends AsyncTask<String, Integer, String> {
private Context context;
private ProgressDialog pd;
private String strUrl;
public downloadPost(Context context, String url) {
this.context = context;
strUrl = url;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("下載中 ...");
pd.setCancelable(false);
pd.show();
}
@Override
protected String doInBackground(String... params) {
downloadFile(strUrl);
return null;
}
// run Progress
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (pv.DEBUG_MODE) System.out.println(TAG + "values:" + values[0]);
pd.setProgress(values[0]); // update Progress
}
// cancel upload
@Override
protected void onCancelled() {
if (pv.DEBUG_MODE) System.out.println(TAG + "onCancelled");
}
@Override
protected void onPostExecute(String result) {
if (pv.DEBUG_MODE) {
System.out.println("result onPostExecute : " + result);
}
player = new MusicPlayer(saveFileName, skbProgress);
pd.dismiss();
Toast.makeText(LessonContentActivity.this, "下載完成", Toast.LENGTH_SHORT).show();
}
private void downloadFile(String fileUrl) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(fileUrl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File(Environment.getExternalStorageDirectory() + "/easylisten/" + courseId + "/");
if (!SDCardRoot.exists()) {
SDCardRoot.mkdirs();
}
//create a new file, specifying the path, and the filename
//which we want to save the file as.
//file Name : i.am.a.file.jpg || hahaha
//fileUrl : http://solvefzt2.fzt.cc/.../i.am.a.file.jpg || hahaha.png
String realFileName = fileUrl.split("/")[fileUrl.split("/").length - 1];
String fileMime = realFileName.split("\\.")[realFileName.split("\\.").length - 1];
if (pv.DEBUG_MODE) {
System.out.println(TAG + "realFileName:" + realFileName);
System.out.println(TAG + "fileMime:" + fileMime);
}
File file = null;
file = new File(SDCardRoot, realFileName);
if (pv.DEBUG_MODE) {
System.out.println(TAG + "file.isFile SDCardRoot,realFileName:" + SDCardRoot + "/" + realFileName);
}
saveFileName = SDCardRoot + "/" + realFileName;
if (file.isFile()) {
return;
}
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the Progress
publishProgress((int) ((downloadedSize / totalSize) * 100));
fileOutput.flush();
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (IOException e) {
e.printStackTrace();
}
}
}
2015年5月21日 星期四
【Android】HttpURLConnection Get 方法
public static String excuteGet(String targetURL, String urlParameters) {
URL url;
HttpURLConnection conn = null;
try {
//Create connection
url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
// 進行連接,但是實際上get request要在下一句的connection.getInputStream()函數中才會真正發到伺服器
conn.connect();
//Get Response , 取得輸入流,並使用Reader讀取
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
【Android】HttpURLConnection Post 方法
public static String excutePost(String targetURL, String urlParameters) {
URL url;
HttpURLConnection conn = null;
try {
//Create connection
url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false); // Post cannot use caches
conn.setDoInput(true); // Read from the connection. Default is true.
// Output to the connection. Default is false, set to true because post
// method must write something to the connection
conn.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
2015年5月14日 星期四
【Android】系統簡單應用—個人GPS定位(儲存在雲端)
原始碼 GitHub : https://github.com/markcoolhu/GpsTrackingCloud.git
package hu.markcool.mygps;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import ssl.SSLSocketFactoryEx;
public class GpsService extends Service {
private static final String TAG = "GpsService ";
private LocationManager mLocationManager = null;
// The minimum time between updates in milliseconds
private static final int MIN_TIME_BW_UPDATES = 1000 * 30; // 1 minute
// The minimum distance to change Updates in meters
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 50f;
private String deviceId;
private double latitude, longitude;
// Define a listener that responds to location updates
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
// Toast.makeText(getApplicationContext(), "Location Changed, now:" + location, Toast.LENGTH_SHORT).show();
mLastLocation.set(location);
if (location == null) return;
Location dest = new Location(location); //取得現在位置
latitude = dest.getLatitude();
longitude = dest.getLongitude();
Toast.makeText(getApplicationContext(), "Location Changed, now latitude:" + latitude +
", longitude:" + longitude, Toast.LENGTH_SHORT).show();
// save cloud DB
Thread t1=new Thread(postData);
t1.start();
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
// get device id
GetDeviceId gdi = new GetDeviceId();
deviceId = gdi.getDeviceId(this);
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private Runnable postData = new Runnable () {
public void run() {
System.out.println("latitude:" + String.valueOf(latitude));
System.out.println("longitude:" + String.valueOf(longitude));
System.out.println("deviceId:" + deviceId);
// params post use (not json format)
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
params.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
params.add(new BasicNameValuePair("device_id", deviceId));
htmlFormPost(params);
}
};
// process html form post (not image or file post)
private String htmlFormPost(List<NameValuePair> params) {
String httpLink = "http://52.74.67.51/gps_tracking/gps_updata.php";
String resultString = null;
// Instantiate the custom HttpClient
HttpClient httpClient = getNewHttpClient();
// Create a new HttpClient and Post Header
// HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(httpLink);
HttpResponse response;
try {
// Bound to request Entry
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
System.out.println("httpPost :" + httpPost);
// Execute HTTP Post Request
response = httpClient.execute(httpPost);
System.out.println("response code :" + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
// get response string, JSON format data
resultString = EntityUtils.toString(response.getEntity());
} else {
resultString = null;
System.out.println("response not ok, status :" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
System.out.println("HttpPost Exception : " + e.toString());
} finally {
httpClient.getConnectionManager().shutdown();
}
System.out.println("resultString : " + resultString);
return resultString;
}
// ssl process
private HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
【Android】開發中關於Fragment異常的問題(java.lang.IllegalStateException: Fragment not attached to Activity)
剛好遇到這問題, 找了一下, 有個網站有寫到,
http://blog.csdn.net/walker02/article/details/7995407
http://blog.csdn.net/walker02/article/details/7995407
我用到了這方法:
關於Fragment(XXFragment) not attached to Activity 異常。出現該異常,是因為Fragment的還沒有Attach到Activity時,調用了如getResource()等,需要上下文Content的函數。
解決方法,就是等將調用的代碼寫在OnStart()中。
網上還有幾處這樣的參考:http://stackoverflow.com/questions/10919240/fragment-myfragment-not-attached-to-activity
在【getResources().getString(R.string.app_name);】之前增加一個判斷isAdded(),
另外的異常解決辦法的有 http://stackoverflow.com/questions/6870325/android-compatibility-package-fragment-not-attached-to-activity
這個是針對另外一種情況下的解決方式。
【Android】攔截/遮罩返回鍵(BACK KEY)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { //監控/攔截/遮罩返回鍵
return true;
} else if (keyCode == KeyEvent.KEYCODE_MENU) {
//監控/攔截菜單鍵
} else if (keyCode == KeyEvent.KEYCODE_HOME) {
//由於Home鍵為系統鍵,此處不能捕獲,需要重寫onAttachedToWindow()
}
return super.onKeyDown(keyCode, event);
}
訂閱:
文章 (Atom)