SetAsWallpaper/app/src/main/java/net/crystalyx/setaswallpaper/SetWallpaperActivity.java

84 lines
2.6 KiB
Java

package net.crystalyx.setaswallpaper;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
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/")) {
handleStream(intent.getParcelableExtra(Intent.EXTRA_STREAM));
}
}
}
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 {
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
launchWallpaperActivity(inputStream);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void handleStream(Uri uri) {
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
launchWallpaperActivity(inputStream);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void launchWallpaperActivity(InputStream stream) {
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
try {
manager.setBitmap(bitmap);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "Wallpaper set!", Toast.LENGTH_SHORT).show();
}
}