Category: Android

Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device, the HTC Dream, being launched in September 2008.

  • Android ExoPlayer with Fullscreen button

    Android ExoPlayer with Fullscreen button

    Android ExoPlayer

    ExoPlayer is an open-source media player for Android developed by Google. It is designed to be used as a replacement for the Android platform’s built-in media player, and it offers many advanced features such as dynamic adaptive streaming over HTTP (DASH), smooth streaming, and advanced audio playback. ExoPlayer is highly customizable, and it can be easily integrated into any Android app that needs to play audio or video content. It is also designed to be efficient and reliable, with a focus on low-latency playback and smooth audio and video performance. Overall, ExoPlayer is a powerful and versatile media player that offers a great deal of flexibility and control for developers.

    ExoSimplify

    ExoSimplify is an Android library that provides a simplified interface for using ExoPlayer, the open-source media player developed by Google. With ExoSimplify, developers can easily integrate ExoPlayer into their Android apps without having to worry about the complexity of the ExoPlayer API. ExoSimplify provides a set of simple methods that allow developers to quickly and easily play audio and video content using ExoPlayer, and it automatically handles many of the common tasks involved in using ExoPlayer, such as initializing and configuring the player, loading media sources, and displaying video content on the screen. By using ExoSimplify, developers can take advantage of the advanced features and capabilities of ExoPlayer without having to spend a lot of time and effort learning the details of the ExoPlayer API.

    How to install?

    To install ExoSimplify, you will need to add it as a dependency in your Android project.

    To do this, you will need to add the following lines to the dependencies section of your project’s build.gradle file:

    allprojects {
    	repositories {
    		maven { url 'https://jitpack.io' }
    	}
    }

    To do this, you will need to add the following lines to the dependencies section of your app’s build.gradle file:

    implementation 'com.github.sminrana:ExoSimplify:0.9.5'
    

    Once you have added this dependency to your project, you will need to sync your project with Gradle to download and install ExoSimplify. You can do this by clicking the “Sync Project with Gradle Files” button in the Android Studio toolbar. Once ExoSimplify has been installed, you can start using it in your project.

    Learn More About ExoSimplify on GitHub

    Spread the love
  • Download PDF in Flutter using Java on Android

    Downloading PDF file in the user download directory on Android is a very common feature, a lot of app uses PDF viewing and downloading feature.

    I hoped that flutter plugins could solve my problem but they didn’t. Fortunately, it was working great on iOS but it was not on android. So I decided to use my old java code in Flutter using Method Channel.

    First I tried two Flutter plugins one for permission and one for creating a directory.

    flutter pub add path_provider
    flutter pub add permission_handler

    Request permission was very easy and it worked on both iOS and Android

    Future<bool> _requestWritePermission() async {
        await Permission.storage.request();
        var r = await Permission.storage.request();
    
        return r.isGranted;
      }

    Since it was working on iOS, I decided to leave that code and separate platform code by importing ‘dart:io’ show Platform. Use this code on your onTap action.

    static const channel = MethodChannel('com.flutterframework/test');
    
    bool hasPermission = await _requestWritePermission();
    
    if (hasPermission) {
      if (Platform.isAndroid) {
        final int downloader = await channel.invokeMethod(
          'download',
          <String, String>{'title': title, 'pdf': pdf},
        );
        print(downloader);
      }
    
      if (Platform.isIOS) {
        var dir = await getApplicationDocumentsDirectory();
        if (dir != null) {
          String saveName = "$title.pdf";
          String savePath = "${dir.path}/$saveName";
          print(savePath);
    
          try {
            await Dio().download(pdf, savePath,
                onReceiveProgress: (received, total) {
              if (total != -1) {
                var percentage = (received / total * 100);
                print(percentage);
                if (percentage >= 100.0) {
                  ScaffoldMessenger.of(context).showSnackBar(
                      snackMessage(
                          'Download completed, please open Files app.'));
                }
              }
            });
            print("File is saved to download folder.");
          } on DioError catch (e) {
            ScaffoldMessenger.of(context).showSnackBar("Download error");
          }
        }
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(filePermissionError);
    }
    

    Finally, the Java code, create a Java class in your main directory.

    package your_package;
    
    import android.app.DownloadManager;
    import android.content.Context;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    
    public class DownloadHelper {
        public static void downloadPDF(Context context, String title, String pdfUrl) {
            try {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(pdfUrl));
                request.setDescription("MyApp");
                request.setTitle(title);
                // in order for this if to run, you must use the android 3.2 to compile your app
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
    
                if (Build.VERSION.SDK_INT <= 17) {
                    request.setDestinationInExternalFilesDir(context, "Documents", "MyFolder/" + title + ".pdf");
                } else {
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "MyFolder/" + title + ".pdf");
                }
    
                // get download service and enqueue file
                DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }
    

    Call that Java code from MainActivity, my MainActivity in Kotlin

    class MainActivity: FlutterActivity() {
        private val CHANNEL = "com.flutterframework/test";
        private lateinit var channel: MethodChannel
    
        override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
            super.configureFlutterEngine(flutterEngine)
            channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
            channel.setMethodCallHandler { call, result ->
                if (call.method == "download") {
                    val pdfTitle = call.argument<String>("title")
                    val pdfUrl = call.argument<String>("pdf")
                    Log.d("TAG", pdfTitle.toString());
                    Log.d("TAG", pdfUrl.toString());
    
                    DownloadHelper.downloadPDF(this, pdfTitle, pdfUrl);
                }
            }
        }
    }

    Download the complete project on GitHub

    Spread the love
  • How to change the status bar color in Flutter, Android only

    Changing the status bar color is very easy in Flutter. There are a few ways to do this.

    1. Globally in the main function
    import 'package:flutter/services.dart';
    
    void main() {
    
      SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle(
          statusBarColor: Colors.red,
        ),
      );
    
      runApp(
        MyApp()
      );
    }

    2. Globally in the MaterialApp widget in ThemeData

    return MaterialApp(
          title: 'FlutterFramework',
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.light,
          theme: ThemeData(
            primaryColor: Colors.red,
            appBarTheme: AppBarTheme(
              systemOverlayStyle: SystemUiOverlayStyle(
                statusBarColor: Colors.red,
              ),
            ),
          ),
    );

    3. AppBar only

    AppBar(
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Colors.red,
      ),
    )

    Spread the love