رفتن به مطلب
انجمن اندروید ایران | آموزش برنامه نویسی اندروید و موبایل
  • android.png.1fab383bc8500cd93127cebc65b1dcab.png

مشکل پروگرس دیالوگ با اسینک تسک


پست های پیشنهاد شده

سلام 
لطفا راهنمایی کنید 
این کدهبا کد های زید میخوام فایلی رو دانلود و پروگرس بار میزان دانلود شده رو نمایش بده اما پروگرس بار اصلا درست اجرا نمیشه 
یعنی مقدار دانلود شده رو نمایش نمیده 
 

package com.rule.myapplication;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class MainActivity extends AppCompatActivity {
    Button button, button2, button3;
    ImageView imageView;
    ProgressDialog mProgressDialog;
    final DownloadTask downloadTask = new DownloadTask(MainActivity.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        imageView = (ImageView) findViewById(R.id.imageView);

        int i = 001 + 002;

        if (i < 10) {
            Toast.makeText(MainActivity.this, "00" + i, Toast.LENGTH_SHORT).show();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadImageFromStorage("/data/data/com.rule.myapplication/part2_button_gallery/part2_button_21");
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                unzip("/data/data/com.rule.myapplication/part2_button_gallery.zip", "/data/data/com.rule.myapplication/part2_button_gallery");
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final DownloadTask downloadTask = new DownloadTask(MainActivity.this);
                downloadTask.execute("http://mehdisamavat.ir/part2_button_gallery.zip");

            }
        });


// instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setMessage("A message");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);


// execute this when the downloader must be fired

        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                downloadTask.cancel(true);
            }
        });

    }


    // usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
    private class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();

                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream("/data/data/com.rule.myapplication/part2_button_gallery.zip");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
//                        publishProgress((int) (total * 100 / fileLength));

                        mProgressDialog.setProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(300);
//            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
        }


    }


    public static Boolean unzip(String sourceFile, String destinationFolder) {
        ZipInputStream zis = null;

        try {
            zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
            ZipEntry ze;
            int count;
            byte[] buffer = new byte[8192];
            while ((ze = zis.getNextEntry()) != null) {
                String fileName = ze.getName();
                fileName = fileName.substring(fileName.indexOf("/") + 1);
                File file = new File(destinationFolder, fileName);
                File dir = ze.isDirectory() ? file : file.getParentFile();

                if (!dir.isDirectory() && !dir.mkdirs())
                    throw new FileNotFoundException("Invalid path: " + dir.getAbsolutePath());
                if (ze.isDirectory()) continue;
                FileOutputStream fout = new FileOutputStream(file);
                try {
                    while ((count = zis.read(buffer)) != -1)
                        fout.write(buffer, 0, count);
                } finally {
                    fout.close();
                }

            }
        } catch (IOException ioe) {
            Log.d("ff", ioe.getMessage());
            return false;
        } finally {
            if (zis != null)
                try {
                    zis.close();
                } catch (IOException e) {

                }
        }
        return true;
    }


    private void loadImageFromStorage(String path) {

        try {
            File f = new File(path, "akhlagh_Page_1.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            imageView.setImageBitmap(b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

کد کامله و داخل یه اکتیویتی میتونید اجرا بگیرید فقط پرمیشن و یه دکمه لازم داره

لینک ارسال
به اشتراک گذاری در سایت های دیگر

از این کلاس استفاده کنید

 

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

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;

/**
 * Created by farzad.sarseify on 13/04/2017.
 */

public class AsyncDownloader extends AsyncTask<String,String,String> {

    // you may separate this or combined to caller class.


    String path_temp,result;
    ProgressDialog pDialog;
    String fileName;

    private AsyncDownloader(){
        //set context variables if required
    }
    public callResponse delegate = null;//Call back interface
    Context context;

    public AsyncDownloader(Context context,String name, callResponse asyncResponse) {
        this.context=context;
        fileName=name;
        delegate = asyncResponse;//Assigning call back interface through constructor
        path_temp = Environment.getExternalStorageDirectory() + File.separator;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Downloading ...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(false);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.show();
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }



    /**
     * In  doInBackground method  translation will be downloading and files saved in Quran folders
     *
     *
     * @param f_url
     * @return  result
     */

    @Override
    protected String doInBackground(String... f_url) {




        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);


            String[] parts=url.toString().split("/");
            result = parts[parts.length - 1];
            // Output stream to write file
            OutputStream output = new FileOutputStream(path_temp+fileName);
            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                //publishProgress(""+(int)((total*100)/lenghtOfFile));
                // writing data to file
                output.write(data, 0, count);
               // publishProgress((int) ((total * 100) / lenghtOfFile)+"");
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                //publishProgress();
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
            DirManagement.deleteFile(path_temp+fileName);

        }

        return path_temp+fileName;

    }



    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        delegate.processFinish(result);
    }


    public interface callResponse {

        void processFinish(String output);
    }

}

 

فراخوانی :

AsyncDownloader    asyncTask; //defind object

		asyncTask = new AsyncDownloader(MainActivity.this, "translation.sqlite", new AsyncDownloader.callResponse() {
                            @Override
                            public void processFinish(String output) {

                               //result and path saved file

                            }
                        });

                        try {
                            asyncTask.execute(download_path);

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

 

 

لینک ارسال
به اشتراک گذاری در سایت های دیگر

به گفتگو بپیوندید

هم اکنون می توانید مطلب خود را ارسال نمایید و بعداً ثبت نام کنید. اگر حساب کاربری دارید، برای ارسال با حساب کاربری خود اکنون وارد شوید .

مهمان
ارسال پاسخ به این موضوع...

×   شما در حال چسباندن محتوایی با قالب بندی هستید.   حذف قالب بندی

  تنها استفاده از 75 اموجی مجاز می باشد.

×   لینک شما به صورت اتوماتیک جای گذاری شد.   نمایش به صورت لینک

×   محتوای قبلی شما بازگردانی شد.   پاک کردن محتوای ویرایشگر

×   شما مستقیما نمی توانید تصویر خود را قرار دهید. یا آن را اینجا بارگذاری کنید یا از یک URL قرار دهید.

  • مطالب مشابه

    • توسط alireza123
      سلام
      من یه لیست بی پایان با ریسایکرویو ساختم . زمانی که به انتهای  اون مقداری که از سرور می گیریه دوباره از یه کلاس asyntask  فراخوانی میشه . کدها رو در پایین قرار دارم. درست کار میکنه ولی هنگامی که اسکرول سریع میدم غاطی می کنه لودینگ متوقف نمیشه کل و پروسه پایان لیست دیگه متوقف میشه کار نمی کنه . مشکل از کجاس؟ و میخواستم بدونم برای متوقف کردن اجرا کلاس asynctask  چی کار باید کرد؟
      public class home_agahi_server extends AsyncTask<String,Void,String> { private Context c; private Activity ac; private String state_id; private String lim; private RecyclerView rec; home_agahi3_server mTask = null; private final ReentrantLock lock = new ReentrantLock(); private final Condition tryAgain = lock.newCondition(); private volatile boolean finished = false; public home_agahi_server(Context c,Activity ac,String lim ){ this.c=c; this.ac=ac; this.lim=lim; this.state_id=state_id; _name.clear(); _id.clear(); _body.clear(); _img.clear(); _imgs.clear(); _price.clear(); _color.clear(); _size.clear(); _shenas.clear(); _time.clear(); _expire.clear(); _visit_today.clear(); _visit_total.clear(); _mobile.clear(); _cat.clear(); _user_id.clear(); _menu_order.clear(); _link.clear(); } @Override protected void onPreExecute() { super.onPreExecute(); //swipeContainer.setRefreshing(false); agahi_recycler.setVisibility(View.GONE); } @Override protected String doInBackground(String... strings) { try { String data = URLEncoder.encode("get_post", "UTF-8") + "=" + URLEncoder.encode("true", "UTF-8"); // data+="&"+ URLEncoder.encode("state_id", "UTF-8")+"="+URLEncoder.encode(state_id,"UTF-8"); data += "&" + URLEncoder.encode("lim", "UTF-8") + "=" + URLEncoder.encode(lim, "UTF-8"); // URL url = new URL(MainActivity.url + "post.php"); URLConnection connect = url.openConnection(); connect.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream()); wr.write(data); wr.flush(); // InputStreamReader in = new InputStreamReader(connect.getInputStream()); BufferedReader reader = new BufferedReader(in); String line = ""; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { Toast.makeText(c, "error in server", Toast.LENGTH_SHORT).show(); return "er"; } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // rotat1.stop(); //swipeContainer.setRefreshing(false); swipeContainer.post(new Runnable() { @Override public void run() { swipeContainer.setRefreshing(false); } }); agahi_recycler.setVisibility(View.VISIBLE); swipeContainer.setVisibility(View.VISIBLE); JSONArray arr=null; JSONObject ob=null; // Toast.makeText(c,s,Toast.LENGTH_SHORT).show(); try{ arr=new JSONArray(s); for(int i=0;i<arr.length();i++){ ob=arr.getJSONObject(i); _name.add(ob.getString("title")); _id.add(ob.getString("id")); _body.add(ob.getString("content")); _img.add(ob.getString("img")); _imgs.add(ob.getString("imgs")); _price.add(ob.getString("price")); _color.add(ob.getString("color")); _size.add(ob.getString("size")); _shenas.add(ob.getString("shenas")); _time.add(ob.getString("time")); _expire.add(ob.getString("expire")); _visit_today.add(ob.getString("todayvisit")); _visit_total.add(ob.getString("totalvisit")); _mobile.add(ob.getString("mobile")); _cat.add(ob.getString("cat")); _user_id.add(ob.getString("user")); _menu_order.add(ob.getString("order")); _link.add(ob.getString("link")); } final AgahiRecyclerAdapter adapter=new AgahiRecyclerAdapter(getActivity().getApplicationContext(), getActivity() ,_name ,_id, _cat, _body , _img, _imgs, _price, _size, _color, _mobile, _visit_today, _visit_total ,_expire ,_shenas ,_time ,_menu_order ,_user_id ,_link ); agahi_recycler.setAdapter(adapter); Display display = getActivity().getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float density = getResources().getDisplayMetrics().density; float dpWidth = outMetrics.widthPixels / density; int columns = Math.round(dpWidth/300); final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),columns); agahi_recycler.setLayoutManager(mLayoutManager); agahi_recycler.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy < 0) { rotat2.stop(); // mTask.cancel(true); } } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { int totalItemCount = mLayoutManager.getItemCount(); int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition(); if (totalItemCount > 1) { if (lastVisibleItem >= totalItemCount - 1) { // End has been reached // do something limit += 6; if (limit < total && scroll == 0 && !rotat2.isStart()) { scroll = 1; mTask = new home_agahi3_server(getActivity().getApplicationContext(), getActivity(), limit + "", adapter ); mTask.executeOnExecutor(mTask.THREAD_POOL_EXECUTOR, ""); } } else { } } } }); }catch (Exception e){ //Toast.makeText(c,"errors in json",Toast.LENGTH_SHORT).show(); } } }  
    • توسط spns33
      سلام
      من تازه برنامه نویسی اندروید را شروع کردم؛امروز داشتم با AsyncTask کار میکردم به یه مشکلی بر خوردم:
      من با AsyncTask یه شمارنده ای را درست کردم که عدد را خودکار شمارش میکنه و داخل TextViwe نمایش میده.
      با باتن OTHER PAGE وارد اکتیویتی دوم میشه و داخل اون یک باتن هست که یک عدد را افزایش میده.
      باتن ABOUT هم صفحه وب را باز میکنه.
      باتن TIME هم فعلا کاری انجام نمیده.
      مشکل اینجاست ، زمانی که بک میزنم و از برنامه بیرون میام دوباره که وارد مشم داخل TextViwe هیچ چیزی نشون نمیده.
      من فکر میکنم مشکل از AsyncTask که داخل MainActivity هست باشه.
      activity_main.xml:
      <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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.app1012.myapplication1012.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/BUT01" android:text="@string/button1" android:textSize="25sp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/BUT02" android:layout_marginTop="25dp" android:text="@string/button2" android:textSize="25sp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/BUT03" android:layout_marginTop="25dp" android:text="@string/time" android:textSize="25sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:layout_gravity="center" android:id="@+id/TEV02"/> </LinearLayout> MainActivity.java:
      package com.example.app1012.myapplication1012; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { /*Thread mythread=new Thread(){ public void run(){ while (true) { try { m++; sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } };*/ int m = 0; String CC; TextView TEXVV; TxtTimer TxtTimer1=new TxtTimer(); boolean d=true; public void TextUp(Integer inpu_t) { CC = Integer.toString(inpu_t); TEXVV.setText(CC); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button BUTJ1 = (Button) findViewById(R.id.BUT01); Button BUTJ2 = (Button) findViewById(R.id.BUT02); Button BUTJ3 = (Button) findViewById(R.id.BUT03); TEXVV = (TextView) findViewById(R.id.TEV02); //mythread.start(); TxtTimer1.execute(); BUTJ1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent otactiv = new Intent(MainActivity.this, Other_page.class); startActivity(otactiv); } }); BUTJ2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent abactive = new Intent(Intent.ACTION_VIEW, Uri.parse("http://site.ir")); startActivity(abactive); } }); BUTJ3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } @Override protected void onPause() { super.onStop(); d=false; } @Override protected void onResume() { super.onResume(); d=true; } private class TxtTimer extends AsyncTask<Object, Integer, Boolean> { @Override protected Boolean doInBackground(Object... strings) { while (m<=1000000) { if (d == true) { // کد زیر متد پروگرس رو صدا میزنه و بهش مقدار پیشرفت رو میدیم publishProgress(m, 1000000); try { m++; Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } /*if(TxtTimer1.isCancelled()){ s=false; } else { s=true; }*/ return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // ma do meghdar be method emun dadim, yeki meghdar pishraft dovomi kole pishraft ke dar zir be tartib una ro estefade kardim TextUp(values[0]); } @Override protected void onPostExecute(Boolean s) { super.onPostExecute(s); } } } string.xml:
      <resources> <string name="app_name">My Application1012</string> <string name="button1">OTHER PAGE</string> <string name="button2">ABOUT</string> <string name="Count">COUNTER</string> <string name="time">TIME</string> </resources> AndroidManifest.xml:
      <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.app1012.myapplication1012"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Other_page"> <intent-filter> <action android:name="android.intent.action.Other_page" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> otherpage.xml:
      <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp" android:id="@+id/other"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TEV01" android:layout_gravity="center"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/oBUT" android:text="@string/Count" android:textSize="25sp" android:layout_marginTop="25dp"/> </LinearLayout> Other_page.java:
      package com.example.app1012.myapplication1012; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Other_page extends AppCompatActivity { int i=0; TextView TEVJ; @Override protected void onCreate(Bundle savedInstanceState2) { super.onCreate(savedInstanceState2); setContentView(R.layout.otherpage); Button oBUTJ=(Button)findViewById(R.id.oBUT); TEVJ=(TextView)findViewById(R.id.TEV01); oBUTJ.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i++; String COU=Integer.toString(i); TEVJ.setText(COU); } }); } } پیشاپیش از راهنماییتون ممنونم.
    • توسط behrad9912
      سلام اینم یه آموزش خوب مخصوص شما
      ابتدا سمت سرور تو File manager یه فولدر میسازید به اسم upload سپس کنارش یه فایل با پسوند php میسازید و کد زیرو توش قرار میدید.اسم فایل هم upload.php باشه
      <?php $target_path1 = "upload/". basename( $_FILES['uploaded_file']['name']); move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1); ?>   خب حالا از کد زیر استفاده کنید در سمت اندروید

       
      private void upload(String sfile) {//sfile addrese file roye device int fbyte, buffersize, cbuffer; int maxbuffer = 1024 * 1024; File f = new File(sfile); try { FileInputStream fis = new FileInputStream(f); /////////////////////////// URL url = new URL("");//file samte server /////////////////////////////////////////////// HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setUseCaches(false); con.setRequestProperty("Connection", "keep-Alive"); con.setRequestProperty("ENCType", "multipart/form-data"); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****"); con.setRequestProperty("uploaded-file", sfile); DataOutputStream dos = new DataOutputStream(con.getOutputStream()); dos.writeBytes("--*****\r\nContent-Disposition: form-data; name=\"uploaded_file\"; filename=\"" + sfile + "\"\r\n\r\n"); fbyte = fis.available(); buffersize = Math.min(fbyte, maxbuffer); byte[] buffer = new byte[buffersize]; cbuffer = fis.read(buffer, 0, buffersize); while (cbuffer > 0) { dos.write(buffer, 0, buffersize); fbyte = fis.available(); buffersize = Math.min(fbyte, maxbuffer); cbuffer = fis.read(buffer, 0, buffersize); } dos.writeBytes("\r\n--*****--\r\n"); if (con.getResponseCode() == 200) { runOnUiThread(new Runnable() { @Override public void run() { Log.e("upload","uploaded"); } }); fis.close(); dos.flush(); dos.close(); } } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { Log.e("error",e+""); di.dismiss(); } }); } }  
      سوالی بود در خدمتم
    • توسط behrad9912
      سلام خیلیییی وقت بود نبودم این آموزش مخصوص دوستانی که نیاز دارن عکسی از نت لود کنن
       
      private class DIT extends AsyncTask { String Url; ImageView view; private DIT(String url,ImageView img) { Url = ""; view =img; } protected Bitmap doInBackground(String... arg0) { // TODO Auto-generated method stub Bitmap mi = null; try { InputStream im = new URL(Url).openStream(); mi = BitmapFactory.decodeStream(im); } catch (Exception e) { } return mi; }  
      مقدار Url که مشخصه لینک عکستون هست ImageView هم همون ImageView ی هست که میخواد عکس توش قرار بگیره.
      نحوه اجرا این کد اینه که اون جایی که خواستید این دستور رو وارد کنید.
       
      new DIT(link,img).execute();  
    • توسط Majid Ebrahimi
      در این آموزش می خواهیم دانلود فایل در دیالوگ باکس با قابلیت لغو دانلود را برای شما آموزش دهیم ابتدا کد برنامه:
       
      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.ProgressDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; public class DownloadActivity extends Activity { /** Called when the activity is first created. */ boolean isRun = false; ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new DownloadFileFromURL().execute("http://hw14.asset.aparat.com/aparat-video/1d7288ace5ce9cc812f6cf5b99d2b8b62642090-360p__87605.mp4"); isRun = true; } private final class onCancelClick implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface arg0, int arg1) { isRun = false; } } class DownloadFileFromURL extends AsyncTask { private ProgressDialog pDialog; /** * Before starting background thread * Show Progress Bar Dialog * */ @SuppressWarnings("deprecation") @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(DownloadActivity.this); pDialog.setMessage("موسیقی مورد نظر در حال دانلود است..."); pDialog.setIndeterminate(false); pDialog.setMax(100); pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(false); pDialog.setButton("لغو", new onCancelClick()); pDialog.show(); } /** * Downloading file in background thread * */ @Override protected String doInBackground(String... f_url) { int count; try { URL url = new URL(f_url[0]); URLConnection conection = url.openConnection(); conection.connect(); // getting file length int lenghtOfFile = conection.getContentLength(); // input stream to read file - with 8k buffer InputStream input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file File f = new File("sdcard/ff.mp3"); OutputStream output = new FileOutputStream(f); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called publishProgress("" + (int) ((total * 100) / lenghtOfFile)); // writing data to file output.write(data, 0, count); if ( !isRun) { f.delete(); break; } } // flushing output output.flush(); // closing streams output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } @Override protected void onProgressUpdate(String... progress) { pDialog.setProgress(Integer.parseInt(progress[0])); } @SuppressWarnings("deprecation") @Override protected void onPostExecute(String file_url) { pDialog.dismiss(); } } }  
      همانطور که مشهود است از یک کلاس آسینک تسک استفاده شده برای دانلود فایل و پس از تنظیمات اولیه دیالوگ در متد onPreExecute در متد doInBackground کارهای اصلی انجام می شود. که فایل دانلود و در اس دی کارد نوشته یا ذخیره می شود اما قسمت مهم این کار متغیر isRun است که پس از هربار نوشتن چک می شود که آیا کاربر دانلود را متوقف کرده یا نه که اگر نکرده به دانلود ادامه دهد و اگر دکمه توقف توسط کاربرد زده شده دانلود را متوقف می کند.
      اما باید توجه داشته باشبید که پرمیشن های زیر را در فایل منیفست اضافه کنید.
       
      امیدوارم این آموزش راهنمای خوبی برای شما دوستان باشد.
  • فایل

×
×
  • اضافه کردن...