Monday, June 26, 2017

Lamda Expression 2

package calculator;

public class Calculator {
  
    interface IntegerMath {
        boolean check(int a); 
    }
  
     public boolean operateBinary(IntegerMath op, int x) {
        //return op.operation(a, b);
        //return op.operation(x, y, z);
        return op.check(x);
    }

    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        

        IntegerMath mycheck = (a) -> a == 90;
        
        System.out.println("is a equal to 90?= " +
            myApp.operateBinary(mycheck, 40));
        
    }
}




Generic Interface




http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

The interface Predicate is an example of a generic interface. 

Generic types (such as generic interfaces) specify one or more type parameters within angle brackets (<>). 
This interface contains only one type parameter, T

When you declare or instantiate a generic type with actual type arguments, you have a parameterized type.


Lambda Expression

public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax



package calculator;

public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b, int c); 
    }
  
    public int operateBinary(IntegerMath op, int x, int y, int z) {
        //return op.operation(a, b);
        return op.operation(x, y, z);
    }

    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        
        IntegerMath addition = (a, b, c) -> a + b + c;
        IntegerMath subtraction = (a, b, c) -> a - b - c;
        
        System.out.println("40 + 2 = " +
            myApp.operateBinary(addition, 40, 20, 10));
        
        System.out.println("20 - 10 = " +
            myApp.operateBinary(subtraction, 20, 10, 5));    
    }
}



Simple Java Code - calling another method

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package helloworldapp;

/**
 *
 * @author Kent Lau
 */
public class HelloWorldApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("Hello World!");
       
        int testscore = 76;
        char grade;
       
       
        System.out.println("Grade = " + testMyScore(testscore));
    }
   
    public static char testMyScore(int score) {
    //do the calculation here
   
        if (score >= 90) {
            return 'A';
        } else if (score >= 80) {
            return 'B';
        } else if (score >= 70) {
            return 'C';
        } else if (score >= 60) {
            return 'D';
        } else {
            return 'F';
        }
    }
   
}

Thursday, February 16, 2017

Wednesday, June 6, 2012

Android Advance Training: Autoreply sender via BoardcastReceiver




Complete Code
package com.k;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver2 extends BroadcastReceiver{

       @Override
       public void onReceive(Context context, Intent intent) {
             
              // Get the SMS message pass in
              Bundle bundle = intent.getExtras();
              String sOutput = "";
             
              if (bundle != null) {
                    
                     // Retrieve the SMS message received
                     Object[] pdus = (Object[]) bundle.get("pdus");
                    
                     SmsMessage[] smsMessage = new SmsMessage[pdus.length];
                    
                     for (int n = 0; n < smsMessage.length; n++) {
                          
                           smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]);
                          
                           sOutput += "SMS from " + smsMessage[n].getOriginatingAddress();
                           sOutput += " : ";
                           sOutput += smsMessage[n].getMessageBody().toString();
                           sOutput += "\n";
                     }
                    
                     // Show the new SMS message
                     Toast.makeText(context, sOutput, Toast.LENGTH_SHORT).show();
                    
                     // Send a broadcast intent to tell the activity about the new SMS received
                     Intent broadcastIntent = new Intent();
                     broadcastIntent.setAction("SMS_RECEIVED_ACTION");
                     broadcastIntent.putExtra("sms", sOutput);
                     context.sendBroadcast(broadcastIntent);
                    
              }

       }

}

package com.k;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class SMSReceiveAppActivity extends Activity {
      
       Button btnSendSMS;
       IntentFilter intentFilter;
      
       private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
             
       @Override
       public void onReceive(Context context, Intent intent) {
             
              // display the SMS received in the TextView
              TextView SMSes = (TextView) findViewById(R.id.textView1);
              SMSes.setText(intent.getExtras().getString("sms"));

                try {
                      
                     String sms = "Testing by Kent";
                      
                     SmsManager smsManager = SmsManager.getDefault();
                     smsManager.sendTextMessage("5554", null, sms, null, null);
                    
                     Toast.makeText(getApplicationContext(), "Your SMS is sent successfully!",
                                         Toast.LENGTH_LONG).show();
                    
                } catch (Exception e) {
                      
                     Toast.makeText(getApplicationContext(),
                           "Sending SMS faild!",
                           Toast.LENGTH_LONG).show();
                    
                }
      
       }
      
       };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //---intent to filter for SMS messages received---
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");


       
       
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        btnSendSMS.setOnClickListener( new View.OnClickListener() {
             
        public void onClick(View v)
        {
             
        //sendSMS(“5554”, “Hello my friends!”);
        Intent i = new Intent(android.content.Intent.ACTION_VIEW);
        i.putExtra("address", "5554");
        i.putExtra("sms_body", "Hello my friends!");
        i.setType("vnd.android-dir/mms-sms");
       
        startActivity(i);
        }
        });
       
    }

    @Override
    protected void onResume() {
    //---register the receiver---
    registerReceiver(intentReceiver, intentFilter);
    super.onResume();
    }
   
    @Override
    protected void onPause() {
    //---unregister the receiver---
    unregisterReceiver(intentReceiver);
    super.onPause();
    }
   
    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {
    //...
    }
   
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.k"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SMSReceiveAppActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
              <receiver android:name=".SMSReceiver" android:enabled="true">
                     <intent-filter>
                           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                     </intent-filter>
              </receiver>
             
                     <receiver android:name=".SMSReceiver2">
                           <intent-filter>
                           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                           </intent-filter>
                     </receiver>
                          
       
    </application>
    <uses-permission android:name="android.permission.SEND_SMS" />
       <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
   
</manifest>