Showing posts with label android buzz. Show all posts
Showing posts with label android buzz. Show all posts

Model View View-Model (MVVM): Getting Started

Android MVVM 

MVVM stands for ModelViewViewModel.

Model: This app contains data. He cannot speak directly to the scenario. In general, it is recommended to expose the data to the viewmodel by the observables.

View: It represents the UI of any application logic-free application. It observes the viewmodel.

ViewModel: It acts as a link between the model and the view. It is responsible for transforming the data from the model. It provides the data stream to the view. It also uses hooks or callback to update the view. It wants data from the model.

The following flow describes the main MVVM pattern.

android architecture or Android software stack

or Android software stack is categorized into five parts:


  1. linux kernel
  2. native libraries (middleware),
  3. Android Runtime
  4. Application Framework
  5. Applications


Let's see the android architecture first.



1) Linux kernel

It is the Android system design in the Android design. The Linux kernel is responsible for device drivers, power management, memory management, device management, and asset acquisition.

2) ancient libraries
The library's first library, such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc), is at the top of the Linux Lunar Calendar.

The WebKit library is responsible for browser support, SQLite support, font support, FreeType for font support, audio and video formats for media playback.


3) Android Runtime
The main library in the android program and the DVM (Dalvik Virtual Machine) are responsible for running the android application. DVM, like JVM, is optimized for mobile devices. It uses less memory and provides faster performance.


4) Android Framework
There is a android framework on top of libraries and on the top of Android. Android API as an Android API, such as UI (UI), telephony, resources, locations, content providers (data), and bundled administrators. Includes. Enriching the Android application provides you with lots of features and interactions.


5) Applications
There are apps on the top of the Android infrastructure. All apps, such as home, contacts, settings, games and browsers are android configurations that use android launcher and libraries. Android Run and Native Libraries are using linux kernal. 

firebase push notification android example

firebase push notification android example 

In recent times, Google moved from Google Cloud Messaging (GCM) to Firebase Cloud Messaging (FCM). Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations.
If you have followed any of my previous tutorials about GCM, I strongly recommend you migrate to Firebase today itself. In this article we learn the features of firebase cloud messaging by building a simple app. We’ll also learn how to integrate firebase to your backend, so that you can send the messages from your server.

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<service android:name=".firebase.FireIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>
<service android:name=".firebase.FireMsgService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

build.gradle Project

classpath 'com.google.gms:google-services:3.1.0'

build.gradle App

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
compile 'com.google.firebase:firebase-messaging:11.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
apply plugin: 'com.google.gms.google-services'

FireIDService.java
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class FireIDService extends FirebaseInstanceIdService {
    @Override    public void onTokenRefresh() {
        String tkn = FirebaseInstanceId.getInstance().getToken();
        Log.d("Device Token","Token ["+tkn+"]");
    }
}

FireMsgService.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.firebasedemo.activity.MainActivity;
import com.firebasedemo.R;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/** * Created by Rid's Patel on 22-04-2018. */
public class FireMsgService extends FirebaseMessagingService {

    @Override    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("Msg", "Message received ["+remoteMessage+"]");

        // Create Notification        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = new                NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Message")
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410, notificationBuilder.build());
    }
}


How to download file in url Android 8 Oreo

How to download file in URL Android 8 Oreo.




new DownloadFileFromURL(position).execute(data.get(url));

private class DownloadFileFromURL extends AsyncTask<String, String, String> {
    private ProgressDialog p;
    private int pos = 0;

    public DownloadFileFromURL(int p) {
        pos = p;
    }

    @Override    protected void onPreExecute() {
        super.onPreExecute();
        p = new ProgressDialog(context);
        p.setMessage("Downloading 0%");
        p.setIndeterminate(false);
        p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        p.setCancelable(false);
        p.show();
    }

    @Override    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        p.setMessage("Downloading " + values[0] + "%");
    }

    @Override    protected String doInBackground(String... f_url) {
        int count;
        String filename = f_url[0];
        String[] parts = filename.split("/");
        String part2 = parts[parts.length - 1];
        Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        File myNewFolder = null;
        if (isSDPresent) {
            String newFolder = "/patelwala";
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            myNewFolder = new File(extStorageDirectory + newFolder);
            if (myNewFolder.exists()) {
            } else {
                myNewFolder.mkdirs();
            }
        } else {
            String newFolder = "patelwala";
            myNewFolder = context.getDir(newFolder, Context.MODE_PRIVATE);
            if (!myNewFolder.exists()) {
                myNewFolder.mkdirs();
            }
        }
        try {
            System.out.println("Downloading");
            URL url = new URL(f_url[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file            OutputStream output = new FileOutputStream(myNewFolder + "/" + part2);
            byte data[] = new byte[1024];

            long total = 0;
            while ((count = input.read(data)) != -1) {
                //if (!Webservice.isCancelled) {                total += count;

                // writing data to file                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
              /*  } else {                    break;                }*/
            }
            // flushing output            output.flush();
            // closing streams            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return myNewFolder + "/" + part2;
    }


    /**     * After completing background task     **/    @Override    protected void onPostExecute(String s) {
        p.dismiss();
        openDocument(s);
    }

}



public void openDocument(String name) {
    if (co == 0) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(name);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (extension.equalsIgnoreCase("") || mimetype == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file            intent.setDataAndType(Uri.fromFile(file), "text*//*");
        } else {
            intent.setDataAndType(Uri.fromFile(file), mimetype);
        }
        // custom_alert_dialog message for the intent        context.startActivity(Intent.createChooser(intent, "Choose an Application:"));
    } else {
        co = 0;

        File f = new File(name);
        Uri uri = Uri.parse("file://" + f.getAbsolutePath());
        Intent share = new Intent(Intent.ACTION_SEND);
        //  share.putExtra(Intent.EXTRA_STREAM, uri);        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (extension.equalsIgnoreCase("") || mimetype == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file            share.setType("text*//*");
        } else {
            share.setType(mimetype);
        }
        share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(Intent.createChooser(share, "Share File"));

    }

}