원격으로 이미지를 다운로드하는 지침을 따라 왔지만 인터넷 연결이있을 때 제대로 작동하지만 인터넷 연결이없는 상태로 활동을 시작하면 활동 충돌 "강제 종료"Android 인터넷 연결이없는 경우 활동 중단 (FC)을하는 데 도움이됩니다.
저는 안타깝게도 안드로이드 초보자입니다. 그래서 충돌을 막기 위해 무엇을해야할지 모르겠습니다. 그들의 화면은 빈 화면으로 "죄송합니다 인터넷이 필요합니다"라는 메시지를 축하하는 것입니다. 그냥 멈추기 만하면됩니다. 사람이 어떻게 이렇게하는 저를 보여줄 수
희망, 감사합니다 루시
private ImageAdapter imageAdapter;
private ArrayList<String> PhotoURLS = new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.galleryview);
public static boolean isDataConnectionAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info == null)
return false;
return connectivityManager.getActiveNetworkInfo().isConnected();
}
imageAdapter = new ImageAdapter(this);
final ImageView imgView = (ImageView) findViewById(R.id.GalleryView);
Gallery g = (Gallery) findViewById(R.id.Gallery);
g.setAdapter(imageAdapter);
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
imgView.setImageDrawable(LoadImageFromURL(PhotoURLS
.get(position)));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
}
});
// replace this code to set your image urls in list
PhotoURLS.add("http://domain.com/image-286.jpg");
PhotoURLS.add("http://domain.com/image-285.jpg");
PhotoURLS.add("http://domain.com/image-284.jpg");
PhotoURLS.add("http://domain.com/image-283.jpg");
PhotoURLS.add("http://domain.com/image-282.jpg");
PhotoURLS.add("http://domain.com/image-281.jpg");
new AddImageTask().execute();
}
class AddImageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... unused) {
for (String url : PhotoURLS) {
String filename = url.substring(url.lastIndexOf("/") + 1,
url.length());
filename = "th_" + filename;
String thumburl = url.substring(0, url.lastIndexOf("/") + 1);
imageAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
publishProgress();
//SystemClock.sleep(200);
}
return (null);
}
@Override
protected void onProgressUpdate(Void... unused) {
imageAdapter.notifyDataSetChanged();
}
@Override
protected void onPostExecute(Void unused) {
}
}
private Drawable LoadThumbnailFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufferedHttpEntity.getContent();
Drawable d = Drawable.createFromStream(is, "src Name");
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
private Drawable LoadImageFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
entity);
InputStream is = bufferedHttpEntity.getContent();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 320;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp/2 < REQUIRED_SIZE
|| height_tmp/2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
is = bufferedHttpEntity.getContent();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeStream(is, null, o2);
Drawable d = new BitmapDrawable(b);
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
ArrayList<Drawable> drawablesFromUrl = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.GalleryTheme);
mGalleryItemBackground = a.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
a.recycle();
}
public void addItem(Drawable item) {
drawablesFromUrl.add(item);
}
public int getCount() {
return drawablesFromUrl.size();
}
public Drawable getItem(int position) {
return drawablesFromUrl.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageDrawable(drawablesFromUrl.get(position));
i.setLayoutParams(new Gallery.LayoutParams(70, 110));
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
//i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
안녕하세요, 초심자님께 말씀 드린 것처럼 빠른 답장을 보내 주셔서 감사합니다. 그래서 내가 게시 한 코드에 어디에 넣을 지 잘 모르겠습니다. 가능하다면 누군가 코드에서 코드를 추가 할 수 있습니다. 코드 라인은 충돌을 막기 위해 실제로 무엇을하는지 설명합니다. 이렇게하면 앞으로 어떤 일이 일어나고 어떻게 작동 하는지를 기억할 수 있습니다. Thankyou, Lucy – Lucy
위의 코드를 호출하여 isDataConnectionAvailable 함수를 호출하고 true를 반환하면 코드를 실행합니다 ... –
안녕하세요, 위 코드를 추가했는데 (위의 편집 된 코드 참조) 오류가있는 것 같습니다. 내가 한 일을 보거나 더 중요한 일은 제대로 수행하지 못했습니다. 위의 함수를 호출하여 인터넷을 사용할 수있는 경우 나머지 코드를 실행하고 "no internet"이라는 메시지를 인터넷에 토스트하지 않습니다. 지금까지 도와 주셔서 고맙습니다. – Lucy