package net.crystalyx.setaswallpaper; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.Toast; import androidx.core.content.FileProvider; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SetWallpaperActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(intent.getAction()) && type != null) { if ("text/plain".equals(type)) { handleUrl(intent.getStringExtra(Intent.EXTRA_TEXT)); } else if (type.startsWith("image/")) { launchWallpaperActivity(intent.getParcelableExtra(Intent.EXTRA_STREAM), type); } } } private String generateRandomString() { int leftLimit = 97; // letter 'a' int rightLimit = 122; // letter 'z' int targetStringLength = 3; Random random = new Random(); StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } return buffer.toString(); } private void handleUrl(String textUrl) { URL url; try { url = new URL(textUrl); } catch (MalformedURLException e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { try { File outputFile = File.createTempFile(generateRandomString(), generateRandomString(), getCacheDir()); URLConnection connection = url.openConnection(); connection.connect(); InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(outputFile); byte[] data = new byte[1024]; int count; while ((count = inputStream.read(data)) != -1) { outputStream.write(data, 0, count); } outputStream.flush(); outputStream.close(); inputStream.close(); Uri uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", outputFile); launchWallpaperActivity(uri, connection.getContentType()); } catch (IOException e) { e.printStackTrace(); } }); } private void launchWallpaperActivity(Uri uri, String mimeType) { Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setDataAndType(uri, mimeType); intent.putExtra("mimeType", mimeType); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, "Set as:")); } }