简体   繁体   English

使用服务下载图片

[英]Download pictures using a service

I'm trying to download pictures in the background of an app using Service (not IntentSevice) Somehow, my code doesn't work. 我正在尝试使用Service(而不是IntentSevice)在应用程序的背景中下载图片。我的代码无法正常工作。 I set permissions for Internet and Storage in the Manifest. 我在清单中设置了Internet和存储的权限。

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. 我感谢您提出的任何评论或答案(:这是我的代码:对于服务,然后对于MainActivity,我已经尝试了其他链接或httpURLConnection而不是常规的URL连接,但这也不起作用。

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");
            }
        }
    }
 };
 }

服务在主线程上运行,因此存在网络异常。主线程上不允许联网。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM