使用服务下载图片

时间:2017-10-22 14:05:54

标签: java android android-intent service

我正在尝试使用服务(不是IntentSevice)在应用程序的后台下载图片 不知何故,我的代码不起作用。 我在Manifest中设置了Internet和Storage的权限。

我很感谢任何评论或答案(: 这是我的代码: 对于服务,然后是MainActivity 我已经尝试过不同的链接或httpURLConnection而不是普通的URL连接,但这也不起作用。

当我运行应用程序时,它总是显示我的“错误”吐司。它甚至没有进入输入流。

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

1 个答案:

答案 0 :(得分:0)

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