1021Zhoukaozuoye

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="服务器下载图片"
        android:id="@+id/bt1"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="从SD卡读取图片"
        android:id="@+id/bt2"/>


</LinearLayout>

package com.example.threezhoukaotwo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    private ServiceConnection serviceConnection;
    private Button bt1;
    private Button bt2;
    private static final String path ="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);

//        intent = new Intent(this,MyService.class);
//        startService(intent);
//        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Manifest.class);
                startService(intent);
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,SqliteHelp.class);
                intent.putExtra("path",path);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intent);
    }
}
package com.example.threezhoukaotwo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class SqliteHelp extends SQLiteOpenHelper {

    public SqliteHelp(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

package com.example.threezhoukaotwo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
    private static final String path ="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(){
            public void run(){
                if (MyAsynTask.isNetWork(MyService.this)){
                    byte data[] = MyAsynTask.request(path);
                    if (WriteFile.isSDcard()){
                        if (WriteFile.write(data,path)){
                            Intent intent1 = new Intent(MyService.this,MyBroad.class);
                            sendBroadcast(intent1);
                        }else{
                            System.out.println("写入SD卡失败");
                        }
                    }else {
                        System.out.println("SD卡不可用");
                    }
                }else{
                    Toast.makeText(MyService.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        }.start();
        return START_NOT_STICKY;
    }
}

package com.example.threezhoukaotwo;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MyAsynTask {
    public static boolean isNetWork(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();

        if (activeNetworkInfo!=null){
            return true;
        }else{
            return false;
        }
    }
    public static byte[] request(String path){
        ByteArrayOutputStream bo=new ByteArrayOutputStream();
        try {
            URL url = new URL(path);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            if (urlConnection.getResponseCode()==200){
                InputStream inputStream = urlConnection.getInputStream();
                int count = 0;
                byte[] b = new byte[1024];
                while((count=inputStream.read(b))!=-1){
                    bo.write(b,0,count);
                    bo.flush();
                }
            }
            return bo.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

package com.example.threezhoukaotwo;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;

public class WriteFile {
    public static boolean isSDcard(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
        return false;
    }
    public static boolean write(byte data[],String path)   {     boolean flag=false;       try       {        String fileName=path.substring(path.lastIndexOf("/")+1);         File file=new File(Environment.                getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),                fileName);       FileOutputStream fo=new FileOutputStream(file);          fo.write(data);          flag=true;       fo.close();       }     catch (Exception e)       {        e.printStackTrace();      }     return flag;   }

}


package com.example.threezhoukaotwo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroad extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "写入SD卡成功", Toast.LENGTH_SHORT).show();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值