Sunday, May 21, 2017

Firebase Functions (tutorial for mac)

My notes below :)
Only me: Android Studio $cd /dev/Android_code/Functions_Firebase

1. Install Firebase CLI and install Node.js
2. $firebase login
3. Create a new directory

$cd /Users/andres/dev/firebase_Learning/functionsDemo/

4. Open terminal and enter command: $firebase init functions
Command installs functions dependencies
$cd /Users/andres/dev/firebase_Learning/functionsDemo/functions

5. Add your function to file index.js


Add this code to index.js
        var functions = require('firebase-functions');
        var admin = require('firebase-admin');

        admin.initializeApp(functions.config().firebase);

        exports.sendNotification = functions.database.ref('/articles/{articleId}')
        .onWrite(event => {

        // Grab the current value of what was written to the Realtime Database.
        var eventSnapshot = event.data;
        var str1 = "Author is ";
        var str = str1.concat(eventSnapshot.child("author").val());
        console.log(str);

        var topic = "android";
        var payload = {
            data: {
                title: eventSnapshot.child("title").val(),
                author: eventSnapshot.child("author").val()
            }
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });

        });

To deploy run:

$firebase deploy --only functions


Part 2. Create Android App
1. Install Android Studio
2. Create new empty project
3. Below files that we need to create
Architecture:
Model - Article.java
Presenter - MainActivity.java
- MyFirebaseMessagingService.java

4. Open and add MainActivity.java

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("android");
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final EditText titleEditText = (EditText) findViewById(R.id.et_title);
final EditText authorEditText = (EditText) findViewById(R.id.et_author);
Button submitButton = (Button) findViewById(R.id.btn_submit);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseReference myRef = database.getReference("articles").push();
Article article = new Article(titleEditText.getText().toString(),
authorEditText.getText().toString());
myRef.setValue(article);
}
});
}
}

4.5 Add this to main.xml
<?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="code.andres.com.functions_firebase.MainActivity">

    <EditText        android:id="@+id/et_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Title" />

    <EditText        android:id="@+id/et_author"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Author" />

    <Button        android:id="@+id/btn_submit"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Submit" />
</LinearLayout>

5. Create new java class Article.java

public class Article {
    public String title;
    public String author;

    public Article() {
        // Default constructor required for calls to DataSnapshot.getValue(Article.class)    }

    public Article(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

6. Create new java class Article.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("author"));
        }

        // Check if message contains a notification payload.        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String title, String author) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("New Article: " + title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("By " + author)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

7. Add this to AndroidManifext.xml
<service    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>


8. Add to build.gradle
compile 'com.google.firebase:firebase-database:10.0.1'compile 'com.google.firebase:firebase-messaging:10.0.1'




refrenence:
https://code.tutsplus.com/tutorials/serverless-apps-with-firebase-cloud-functions--cms-28557

Thursday, May 4, 2017

Set environment ANDROID_HOME (Mac)

1. Find you sdk location, ex: /Users/engineering/Library/Android/sdk

2. Open terminal and type: $echo export "ANDROID_HOME=/Users/yourName/Library/Android/sdk" >> ~/.bash_profile

3. Close terminal

4. To test environment, open terminal and type: $echo $ANDROID_HOME

Install Google Play Store on Android emulator (using Mac)

After successfully setting up Android Studio and creating a virtual device(android emulator), follow below steps:

A. Download Gapps make selection according to your selected device.
                                                       Ex: using Nexus 6 - API 25 - x86
1. Extract files
$unzip open_gapps-x86-7.1-micro-20170504.zip

$cd Core

2. Install lzip
$brew install lzip

3. Inside /Core extrat files from vending-all.tar.lz
$lzip vending-all.tar.lz

4. Copy Phonesky.apk to home directory
$cp vending-all/240-320-480/priv-app/Phonesky/Phonesky.apk ~/


B. Now Start emulator to push the above Phonesky.apk
1. Start your Android emulator
$./android-sdk/tools/emulator @YourDeviceName -writable-system

2. Open new terminal
$cd ~/android-sdk/platfrom-tools

3. Enter to device's shell
$adb shell
$su

4. Check where directory is mounted
$cat /proc/mounts|grep system

5. Remount
$mount -o rw,remount /dev/block/vda /system
logout shell by clicking Ctrl+d (twice)

6. Push apk
$adb root
$adb push ~/Phonesky.apk /system/priv-app/


7. Restart emulator
./adb shell stop
./adb shell start

Done, now open Google Play Store on your emulator and sign-in.




Reference:
http://linuxoidchannel.blogspot.com/2017/01/how-to-install-google-play-store-on.html

Monday, May 1, 2017

Edit ~/.bash_profile to add shortcuts

 steps:
  1. Open Terminal
  2. $vi ~/.bash_profile
  3. Add below:
  4. alias ll='ls -l'
    alias f='find . -name '
    alias subl='open -a "Sublime Text"'
  5. Done. 
 Open new terminal enter ll

Change Terminal text color

steps:
  1. Open Terminal
  2. $vi ~/.bash_profile
  3. Add below:
  4. export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "
    export CLICOLOR=1
    export LSCOLORS=ExFxBxDxCxegedabagacad
    alias ls='ls -GFh'
  5. Done. Open new terminal now you have color text, 
enter $ls -l

Wednesday, March 15, 2017

Open terminal from any Mac folder

1. Go to System Preferences and select Keyboard > Shortcuts > Services. 
2. check box  "New Terminal at Folder"
3. Done. Now right click in a folder -> services -> open "New Terminal at Folder"

















reference:
lifehacker