2013年8月22日 星期四

Custom Market API / Play Store API

https://play.google.com/store/apps/details?id=com.baseapp.eyeem&hl=en_GB

&hl=en_GB能強制將play store轉成英文

---------------------------------------------------
package com.example.marketapitest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startBtn = (Button)findViewById(R.id.button1);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "https://play.google.com/store/apps/details?id=com.baseapp.eyeem&hl=en_GB";
        new DownloadFileAsync().execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
  case DIALOG_DOWNLOAD_PROGRESS:
   mProgressDialog = new ProgressDialog(this);
   mProgressDialog.setMessage("Downloading file..");
   mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   mProgressDialog.setCancelable(false);
   mProgressDialog.show();
   return mProgressDialog;
  default:
   return null;
        }
    }

class DownloadFileAsync extends AsyncTask<String, String, String> {
 
 @Override
 protected void onPreExecute() {
  super.onPreExecute();
  showDialog(DIALOG_DOWNLOAD_PROGRESS);
 }

 @Override
 protected String doInBackground(String... aurl) {
  int count;

 try {

 URL url = new URL(aurl[0]);
 URLConnection conexion = url.openConnection();
 conexion.connect();

 int lenghtOfFile = conexion.getContentLength();
 Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);



 InputStream input = new BufferedInputStream(url.openStream());
 String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TFFolder";
 File dir = new File(fullPath);
 if (!dir.exists()) {
 dir.mkdirs();
 }
 OutputStream output = new FileOutputStream(fullPath+"/123.txt");



 byte data[] = new byte[1024];

 long total = 0;

  while ((count = input.read(data)) != -1) {
   total += count;
   publishProgress(""+(int)((total*100)/lenghtOfFile));
   output.write(data, 0, count);
  }

  output.flush();
  output.close();
  input.close();
 } catch (Exception e) {}
 return null;

 }
 protected void onProgressUpdate(String... progress) {
   Log.d("ANDRO_ASYNC",progress[0]);
   mProgressDialog.setProgress(Integer.parseInt(progress[0]));
 }

 @Override
 protected void onPostExecute(String unused) {
  dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
 }
}
}

-------------------------------------------------------------------

2013年8月21日 星期三

mysplit

private List<String> mysplit(String input) {
// TODO Auto-generated method stub
List<String> output=new ArrayList();
String temp = "";
for(int i=0;i<input.length();i++){
if(input.toCharArray()[i]!='\\'  )
temp+=input.toCharArray()[i];
else{
output.add(temp);
temp = "";
}

}
output.add(temp);
return output;
}

2013年8月20日 星期二

Android程序完全退出的方法

 System.exit(0);   //常规java、c#的标准退出法,返回值为0代表正常退出

2013年8月19日 星期一

Android Bitmap OOM系列(2):利用convertView/holder 改良GridView

撰寫於2012年09月29日| 沒有評論
      在上一篇日誌《Android Bitmap OOM系列(1):GridView》中,我們已經成功的讓GridView跑起來了,但是這是最最原始的實現方式之一,它的效率也是非常之低(我們的圖片都是來自於項目中,而且都是微小圖片,所以感受不到),一旦圖片的分辨率比較大,而且圖片數量多的話,應用很容易因為內存爆掉而導致FC(Force close)。這是因為我們在getView方法中始終是new一個新的View出來,如此一來,一旦有100張圖,我們就要new 100次,同時當我們滾動GridView的時候,即使是顯示在界面上過的View也會重新new一次。而同時Dalvik虛擬機又未能及時回收已不用的內存,當到達極限時,內存也就理所當然地爆掉了。
      在寫getView這個方法中的代碼時,我們已經發現,getView有一個參數View(參數名為convertView),在android的ListView、Gridview中,convertView是一個很有用,而且很酷的參數。根據官方文檔的解釋,它是用來在可能的情況下重用舊的視圖的。在使用之前,我們應該先檢查這個view不是空的而且是一個適當的類型。所以呢,我們現在就來把getView給改寫一下。改寫後的代碼如下:
View view = null ; 
if  ( convertView ==  null )  { 
 view = mInflater . inflate ( R . layout . gridview ,  null ); 
        ImageView imageView =  ( ImageView ) convertView . findViewById ( R . id . image ); 
 imageView . setImageBitmap ( bitmapList . get ( position )); 
} else { 
        view = convertView
 } 
return view ;
    首先我們判斷convertView是否為空,當為空時,就按照原來的邏輯去xml中尋找控件並實例化出來,然後把BItmap設置進ImageView,如果不為空,就直接將convertView賦給view。
    這次的改寫就這麼簡單,當然這個還是簡單的形式,因為我們現在只有一個ImageView而已,如果在項目中我們GridView的每一個View都是由多個控件組成(比如一個ImageView和一個TextView),那麼我們還需要建一個holder來儲存。首先我們需要建一個holder類(我比較喜歡直接寫在adapter裡作為內部類使用),它只包含2個成員變量
public  class  Holder { 
           public  TextView text ; 
           public  ImageView image ; 
}
然後在getView中使用這個holder,首先我們先實例化Holder為null,然後如同上面那樣判斷convertView是否為空,並進行相應的實例化操作。所不同的是,這裡我們不再需要new 一個ImageView出來了,我們直接把xml中讀出來的ImageView賦值給Holder的成員變量image,TextView也一樣。然後分別給他們設ImageBitamp和Text,之後把Holder設置到convertView裡面去。當convertView不為空的時候,則從convertView中取出相應Holder的視圖出來。
View view = null ; 
Holder holder = null ; 
if  ( convertView ==  null )  { 
 view = mInflater . inflate ( R . layout . gridview ,  null ); 
        holder =  new  Holder (); 
        holder . image =  ( ImageView ) convertView . findViewById ( R . id . image ); 
 holder . image . setImageBitmap ( bitmapList . get ( position )); 
        convertVIew . setTag ( holder ); 
} else { 
        view = convertView . getTag (); 
} 
return view ;
原創文章,轉載請註明:轉載自網憩閣

Google的教學:


getView

static class ViewHolder { 
TextView text; 
ImageView icon; 
}


------------------------------------------------
ViewHolder holder; 

 if (convertView == null) { 
 convertView = mInflater.inflate(R.layout.list_item_icon_text, 
  parent, false);
 holder = new ViewHolder(); 
  holder.text = (TextView) convertView.findViewById(R.id.text); 
  holder.icon = (ImageView) convertView.findViewById(R.id.icon); 

  convertView.setTag(holder); 
  } else { 
  holder = (ViewHolder) convertView.getTag(); 
  } 

  holder.text.setText(DATA[position]); 
  holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2); 

 return convertView; 
-----------------------------------------------------------


public class MyBaseAdapter extends BaseAdapter {

private Context myContext;

MyBaseAdapter(Context c) {
myContext = c;
}
public class ViewHolder { 
TextView text; 
ImageView icon; 
}
@Override
public int getCount() {
return MyAppList.size();
}

@Override
public Object getItem(int position) {
return MyAppList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

/*View MyView = convertView;

if (convertView == null) {

MyView = new View(myContext);
MyView.setLayoutParams(new GridView.LayoutParams(85, 85));
// MyView.setScaleType(View.ScaleType.CENTER_CROP);
MyView.setPadding(8, 8, 8, 8);
} else {
MyView = (View) convertView;
}


LayoutInflater li = getLayoutInflater();
MyView = li.inflate(R.layout.grid_item, null);

// Add The Text!!!
TextView tv = (TextView) MyView.findViewById(R.id.tv);
tv.setText(MyAppList.get(position));

// Add The Image!!!

ImageView iv = (ImageView) MyView.findViewById(R.id.imageView1);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageBitmap(getThumbnail("icon " + MyAppList.get(position)
+ ".png", getBaseContext()));

return MyView;*/

ViewHolder holder; 
LayoutInflater li = getLayoutInflater();
if (convertView == null) { 
convertView = li.inflate(R.layout.grid_item, 
 parent, false);
holder = new ViewHolder(); 
 holder.text = (TextView) convertView.findViewById(R.id.tv); 
 holder.icon = (ImageView) convertView.findViewById(R.id.imageView1); 
 
 convertView.setTag(holder); 
 } else { 
 holder = (ViewHolder) convertView.getTag(); 
 } 
 
 holder.text.setText(MyAppList.get(position)); 
 holder.icon.setImageBitmap(getThumbnail("icon " + MyAppList.get(position)
+ ".png", getBaseContext())); 
 
return convertView; 

}

}

"不再" Force close的 gridview
忽略一些東西, 能換來一些東西

Relative Layout Touch Listener


It may that something in your view is "on top" of myRelativeLayout. If it is, it's getting the touch event first. The worst part about that is that the default handling of events is to do nothing with the event and then consume it.
One solution would be to add this code onto whatever components of your display are "above" the View (or Layout) that SHOULD handle the event:
someView.setOnTouchListener (new View.OnTouchListener()
{
    @Override
    public boolean onTouch (View v, MotionEvent event)
    {
        return false;
    }
});
The key (obviously) is to return false. When you do that, the event will not be consumed, but rather passed "down" to something in your relative layout -- hopefully somewhere you want it to go.
share|improve this answer

2013年8月15日 星期四

launchable activities, as they appear in launcher, without duplicates

I am writing an app that allows user to view the list of installed apps, select one of them and then start it on schedule. Using tutorials from stackoverflow i managed to figure out how to get a list of installed activities, their package names and icons(i.e. here - several ways to do it). Just in case, this is how i start activities, it works flawlessly, no problem here:
Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
The problem is with retrieving a list of installed apps. I've found two ways to get a list of installed applications:
1) use
PackageManager pm = getPackageManager();
List<ApplicationInfo> apps = pm.getInstalledApplication(PackageManager.GET_META_DATA) 
and from each element from apps you can get it's package name and package label(app names).
2) use
PackageManager pm = getPackageManager();    
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(mainIntent, 0);
for(ResolveInfo info : resolveInfos) {
    ApplicationInfo applicationInfo = info.activityInfo.applicationInfo;
    //...
    //get package name, icon and label from applicationInfo object    
}
There is a problem with first method: it returns all installed packages, including system services, which may not contain any activity and are therefore not launchable. Here's a screenshot with an example: app list with packages
All the items above that have no icons are not launchable.
There is a problem with the second approach as well: Several items in the list have duplicates: app list with duplicates
When i set up a breakpoint in debugger i see, that these "Maps" items have different activity names ("com.google.android.maps.MapsActivity", "com.google.android.maps.LatitudeActivity", "com.google.android.maps.PlacesActivity" etc.).
I decided to use the second approach, because it gives a list that is more suitable for my needs, but i can't find a way to filter out the duplicates and only show the default activity for the app, as they appear in the Launcher(you only see one 'Maps' in your phone's list of apps, not four). I've tried filtering out system apps through ApplicationInfo.FLAG_SYSTEM, but this removes many apps that i want to have, including Maps and other preinstalled apps. I've tried usingPackageManager.MATCH_DEFAULT_ONLY flag when executing queryIntentActivities, but this also filters out many apps, leaving just a few.
I'm kinda lost here, and i don't know what to do. I've read all the questions on stackoverflow about retrieving a list of installed apps, but this issue has never been brought up. Please, help anyone? How do i retrieve a list of installed launchable apps that has no duplicates?
share|improve this question
You say that "this issue has never been brought up". Please check this, maybe it helps:stackoverflow.com/questions/4598769/list-of-user-installed-apps/… – Zelimir Mar 28 '12 at 13:50
I meant duplicates in the list, i haven't seen anyone mentioning this. Yes, i've seen that comment, I've tried skipping apps with ApplicationInfo.FLAG_SYSTEM, but for some reason this removes many valid apps, including games and such. – Anton Cherkashyn Mar 28 '12 at 17:45

2 Answers


Intent localIntent2 = new Intent("android.intent.action.PICK_ACTIVITY");
Intent localIntent3 = new Intent("android.intent.action.MAIN",null);
localIntent3.addCategory("android.intent.category.LAUNCHER");   
localIntent2.putExtra("android.intent.extra.INTENT",localIntent3);
startActivityForResult(localIntent2, 1);
Try this code. It will list out only the applications which are all installed in your device.
share|improve this answer
Yes, it worked! Thank you! – Anton Cherkashyn Mar 28 '12 at 18:27
it works but this will be more effective if you can manage to run the selected app. Because as of now when you select an app, nothing happened. – Gangnaminmo Ako Jun 20 at 3:19

Try below code and let me know what happened.
PackageManager manager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> resolveInfos= manager.queryIntentActivities(mainIntent, 0);
// Below line is new code i added to your code
Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(manager));

for(ResolveInfo info : resolveInfos) {
     ApplicationInfo applicationInfo = info.activityInfo.applicationInfo;
     //...
     //get package name, icon and label from applicationInfo object    
}
share|improve this answer
Related Posts Plugin for WordPress, Blogger...