Home » Android » Download pictures using a service

Download pictures using a service

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m trying to download pictures in the background of an app using Service (not IntentSevice)
Somehow, my code doesn’t work.
I set permissions for Internet and Storage in the Manifest.

I’m thankful for any comments or answers (:
Here’s my code:
For the Service and then for the MainActivity
i have already tried different links or httpURLConnection instead of the normal URL connection but that doesnt’t work either.

when I run the app, it always shows my “error” toast. it doesn’t even get to the Input Stream.

public class Download extends Service {


public static final String URL = "url";
public static final String FILENAME = "name";
public static final String FILEPATH = "path";
public static final String RESULT = "result";
public static final String NOTIFICATION = "notification";
public ImageView imageView1 ;

@Override
public IBinder onBind(Intent arg0){
     // TODO Auto-generated method stub
     return null;
 }

public void onCreate(){
    super.onCreate();
    Toast.makeText(this,"Service is created",Toast.LENGTH_LONG).show();

}

 @Override
public int onStartCommand(Intent intent, int flags, int startId){

     String urlPath = intent.getStringExtra(FILEPATH);
     String fileName = intent.getStringExtra(FILENAME);
     int result = Activity.RESULT_CANCELED;

     try {
         Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();

         final URL fileUrl = new URL(urlPath);
         HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();

          final InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
         Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
         //Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();

         File downloadordner = new File(Environment.getExternalStorageDirectory() + "/Pictures");
         if (!downloadordner.exists()) {
             downloadordner.mkdirs();
         }
         File downloadedfile = new File(downloadordner, "Bild1" + System.currentTimeMillis() + ".png");
         OutputStream outputStream = new FileOutputStream(downloadedfile);

         try {
             byte[] buffer = new byte[1024];
             int read;
             while ((read = inputStream.read(buffer)) != -1) {
                 outputStream.write(buffer, 0, read);
             }
             result = Activity.RESULT_OK;
         }finally{


             outputStream.flush();
             outputStream.close();
             inputStream.close();
         }
       } catch (Exception e){
         e.printStackTrace();
         Toast.makeText(this,"Fehler",Toast.LENGTH_LONG).show();

     }
     publishResults(result);
    return START_STICKY;


 }

 private void publishResults(int result){
     Intent intent = new Intent(NOTIFICATION);
     intent.putExtra(RESULT,result);
     sendBroadcast(intent);
 }












 @Override
 public void onDestroy(){

     super.onDestroy();
     Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
     System.exit(0);

 }





}





public class MainActivity extends AppCompatActivity {


Button btn1;
Button btn2;
ProgressBar progbar1;

public ImageView imageView1;
private TextView downloadStatus; //neu

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    downloadStatus = (TextView) findViewById(R.id.download_status);




    progbar1 = (ProgressBar) findViewById(R.id.progbar1);

    btn1 = (Button) findViewById(R.id.go);
    btn2 = (Button) findViewById(R.id.kill);

    imageView1 = (ImageView) findViewById(R.id.bild1);

    btn1.setOnClickListener(onDownloadListener());

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), Download.class));
            System.exit(0);


        }


    });



}

private View.OnClickListener onDownloadListener(){
    return new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,Download.class);
            intent.putExtra(Download.FILENAME,"logo.png");
            intent.putExtra(Download.FILEPATH,"https://de.wikipedia.org/wiki/Kleiner_Eisvogel#/media/File:Limenitis_camilla3.jpg");
            startService(intent);
            downloadStatus.setText("Downloading....");
            Toast.makeText(MainActivity.this, "downloading", Toast.LENGTH_LONG).show();
        }
    };
}



private BroadcastReceiver receiver = new BroadcastReceiver() {
    @SuppressLint("SetTextI18n")
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if(bundle != null){
            int resultCode = bundle.getInt(Download.RESULT);
            if (resultCode == RESULT_OK){
                Toast.makeText(MainActivity.this,"File downloaded",Toast.LENGTH_LONG).show();
                downloadStatus.setText("Download completed");
            }else{
                Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
                downloadStatus.setText("Download failed");
            }
        }
    }
 };
 }
Answers:

Service runs on the main thread so there is a network exception NO networking is allowed on the main thread.