Membuat Aplikasi SMS di Android Studio

Walaupun di android sudah disediakan aplikasi perpesanan bawaan, tetapi tidak ada salahnya kita membuat aplikasi SMS ini, setidaknya untuk mengetahui bagaimana cara kerja dari aplikasi SMS ini, ataupun jika anda ingin membuat aplikasi SMS yang custom, misalnya membuat aplikasi SMS dengan gaya iMessage. Pada kesempatan kali ini akan dibahas cara membuat aplikasi SMS sederhana.



Pertama-tama buat desain tampilannya dulu
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_main"
   
android:padding="10dp"
   
tools:context="com.giviews.message.MainActivity">

    <
RelativeLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content">
        <
EditText
           
android:layout_width="match_parent"
            
android:layout_height="wrap_content"
           
android:inputType="phone"
           
android:ems="15"
           
android:id="@+id/tvNumber"
           
android:hint="Enter contact number"
           
android:singleLine="true" />
    </
RelativeLayout>

    <
LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:orientation="vertical"
       
android:id="@+id/pushingUp"
       
android:layout_alignParentBottom="true"
       
android:layout_alignParentStart="true"
       
android:layout_alignParentLeft="true">
        <
LinearLayout
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:orientation="vertical">
            <
ScrollView
               
android:layout_width="match_parent"
               
android:layout_height="match_parent"
               
android:layout_weight="1">
                <
LinearLayout
                   
android:layout_width="match_parent"
                    
android:layout_height="wrap_content"
                   
android:orientation="vertical">
                    <
TextView
                       
android:layout_width="match_parent"
                       
android:layout_height="match_parent"
                        
android:id="@+id/txtMessage"
                       
android:layout_weight="1"/>
                </
LinearLayout>
            </
ScrollView>
        </
LinearLayout>

        <
LinearLayout
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:orientation="horizontal">
            <
EditText
               
android:layout_width="0dp"
               
android:layout_height="wrap_content"
               
android:ems="160"
                
android:layout_weight="5"
               
android:id="@+id/tvMessage"
               
android:hint="Enter Message"/>
            <
Button
               
android:layout_width="0dp"
               
android:layout_weight="1"
               
android:background="@android:drawable/ic_menu_send"
               
android:layout_height="wrap_content"
               
android:id="@+id/btnSend" />
        </
LinearLayout>
    </
LinearLayout>

</
RelativeLayout>

Kemudian untuk di javanya masukan kode ini
package com.giviews.message;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   
private Button btnSend;
   
private EditText tvMessage;
   
private EditText tvNumber;
    IntentFilter
intentFilter;

   
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
       
@Override
       
public void onReceive(Context context, Intent intent) {
            
//display the message in the textview
           
TextView inTxt = (TextView) findViewById(R.id.txtMessage);
            inTxt.setText(intent.getExtras().getString(
"message"));
        }
    };

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);

       
//intent to filter for SMS message received
       
intentFilter = new IntentFilter();
       
intentFilter.addAction("SMS_RECEIVED_ACTION");

       
btnSend = (Button) findViewById(R.id.btnSend);
       
tvNumber = (EditText) findViewById(R.id.tvNumber);
       
tvMessage = (EditText) findViewById(R.id.tvMessage);

       
btnSend.setOnClickListener(new View.OnClickListener() {
            
@Override
           
public void onClick(View view) {
                String myMsg =
tvMessage.getText().toString();
                String txtNumber =
tvNumber.getText().toString();
                sendMsg(txtNumber, myMsg);
            }
        });
    }

   
private void sendMsg(String txtNumber, String myMsg) {
        String SENT =
"Message Send";
        String DELIVERED =
"Message Delivered";

        PendingIntent sentPi = PendingIntent.getBroadcast(
this, 0, new Intent(SENT), 0);
        PendingIntent deliveredPi = PendingIntent.getBroadcast(
this, 0, new Intent(DELIVERED), 0);

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(txtNumber,
null, myMsg, sentPi, deliveredPi);
    }

   
@Override
   
protected void onResume() {
       
//register the receiver
       
registerReceiver(intentReceiver, intentFilter);
       
super.onResume();
    }

   
@Override
   
protected void onPause() {
       
//unregister the receiver
       
unregisterReceiver(intentReceiver);
        
super.onPause();
    }
}

lalu buatlah class baru di java dengan nama MessageReceiver dan masukan kode ini
package com.giviews.message;

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

/** * Created by asus on 04/10/2017. */
public class MessageReceiver extends BroadcastReceiver {
    @Override    public void onReceive(Context context, Intent intent) {
        //get message passed in        Bundle bundle = intent.getExtras();
        SmsMessage[] messages;
        String str = "";

        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            messages = new SmsMessage[pdus != null ? pdus.length : 0];
            for (int i=0; i<messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) (pdus != null ? pdus[i] : null));
                str += messages[i].getOriginatingAddress();
                str += ": ";
                str += messages[i].getMessageBody();
                str += "\n";
            }

            //display the message            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

            //Send a broadcast intent to update the SMS received in a TextView            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("SMS_RECEIVED_ACTION");
            broadcastIntent.putExtra("messages", str);
            context.sendBroadcast(broadcastIntent);
        }
    }
}

Terakhir tambahkan permission di AndroidManifest untuk mengirim
dan menerima SMS

<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>

dan daftarkan class MessageReceiver
<receiver android:name=".MessageReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

Sekarang coba jalankan di smartphone android anda / di emulator, jika berhasil tampil seperti pada gambar diatas anda sudah berhasil. Ok sekianlah tutorial kali ini Selamat mencoba Semoga bermanfaat kurang dan lebihnya mohon maaf jika ada yang kurang

jelas silakan ditanyakan di komentar

Membuat Aplikasi PDF Reader Sendiri untuk Android Menggunakan Library AndroidPdfViewer

Assalamualikum Wr. Wb, Selamat Sore kali ini admin akan membahas library AndroidPdfViewer yang berguna untuk membuat aplikasi pembaca PDF. Library ini sangat lengkap bisa membuka file PDF lewat asset, lewat Uri untuk dokumentasi lengkap bisa dilihat di github



ok langsung saja untuk membuatnya, pertama-tama masukan despendency ini di modul.gradle:
compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

Kemudian buatlah sebuah button dan PDFView untuk menampilkan pdf nya
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   
tools:context="com.giviews.pdfviewer.MainActivity">

    <
Button
       
android:id="@+id/openpdf"
       
android:text="Browse PDF"
        
android:layout_width="match_parent"
       
android:layout_height="wrap_content" />

    <
com.github.barteksc.pdfviewer.PDFView
       
android:id="@+id/pdfView"
       
android:layout_below="@+id/openpdf"
       
android:layout_width="match_parent"
       
android:layout_height="match_parent"/>

</
RelativeLayout>

Kemudian untuk java nya masukan kode dibawah:
package com.giviews.pdfviewer;



import android.content.ActivityNotFoundException;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.database.Cursor;

import android.graphics.Color;

import android.net.Uri;

import android.os.Bundle;

import android.provider.OpenableColumns;

import android.support.annotation.NonNull;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



import com.github.barteksc.pdfviewer.PDFView;

import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;

import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;

import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;

import com.shockwave.pdfium.PdfDocument;



import java.util.List;



public class MainActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener {

    private static final String TAG = MainActivity.class.getSimpleName();



    private final static int REQUEST_CODE = 42;

    public static final int PERMISSION_CODE = 42042;



    public static final String SAMPLE_FILE = "sample.pdf";

    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";



    private PDFView pdfView;

    private Button openPdf;

    private Uri uri;

    private Integer pageNumber = 0;

    private String pdfFileName;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        pdfView = (PDFView) findViewById(R.id.pdfView);

        openPdf = (Button) findViewById(R.id.openpdf);



        openPdf.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent fileIntent = new Intent();

                fileIntent.setType("application/pdf")

                .setAction(Intent.ACTION_GET_CONTENT);



                int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, READ_EXTERNAL_STORAGE);



                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(

                            MainActivity.this,

                            new String[]{READ_EXTERNAL_STORAGE},

                            PERMISSION_CODE

                    );



                    return;

                }



                startActivityForResult(Intent.createChooser(fileIntent, "SELECT PDF"), REQUEST_CODE);

            }

        });



    }



    void afterViews() {

        pdfView.setBackgroundColor(Color.LTGRAY);

        if (uri != null) {

            displayFromUri(uri);

        } else {

            displayFromAsset(SAMPLE_FILE);

        }

        setTitle(pdfFileName);

    }



    private void displayFromAsset(String assetFileName) {

        pdfFileName = assetFileName;



        pdfView.fromAsset(SAMPLE_FILE)

                .defaultPage(pageNumber)

                .onPageChange(this)

                .enableAnnotationRendering(true)

                .onLoad(this)

                .scrollHandle(new DefaultScrollHandle(this))

                .spacing(10) // in dp

                .load();

    }



    private void displayFromUri(Uri uri) {

        pdfFileName = getFileName(uri);



        pdfView.fromUri(uri)

                .defaultPage(pageNumber)

                .onPageChange(this)

                .enableAnnotationRendering(true)

                .onLoad(this)

                .scrollHandle(new DefaultScrollHandle(this))

                .spacing(10) // in dp

                .load();

    }



    private String getFileName(Uri uri) {

        String result = null;

        if (uri.getScheme().equals("content")) {

            Cursor cursor = getContentResolver().query(uri, null, null, null, null);

            try {

                if (cursor != null && cursor.moveToFirst()) {

                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                }

            } finally {

                if (cursor != null) {

                    cursor.close();

                }

            }

        }

        if (result == null) {

            result = uri.getLastPathSegment();

        }

        return result;

    }





    @Override

    public void loadComplete(int nbPages) {

        PdfDocument.Meta meta = pdfView.getDocumentMeta();

        Log.e(TAG, "title = " + meta.getTitle());

        Log.e(TAG, "author = " + meta.getAuthor());

        Log.e(TAG, "subject = " + meta.getSubject());

        Log.e(TAG, "keywords = " + meta.getKeywords());

        Log.e(TAG, "creator = " + meta.getCreator());

        Log.e(TAG, "producer = " + meta.getProducer());

        Log.e(TAG, "creationDate = " + meta.getCreationDate());

        Log.e(TAG, "modDate = " + meta.getModDate());



        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }



    private void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {

        for (PdfDocument.Bookmark b : tree) {



            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));



            if (b.hasChildren()) {

                printBookmarksTree(b.getChildren(), sep + "-");

            }

        }

    }



    @Override

    public void onPageChanged(int page, int pageCount) {

        pageNumber = page;

        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));

    }



    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            uri = data.getData();

            displayFromUri(uri);

        }

    }

}

terakhir tambahkan permission di manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


sekarang jalankan aplikasinya di smartphone anda / di emulator jika PDF nya terbaca maka anda telah berhasil membuat aplikasi PDF reader. ok sekianlah tutorial kali ini semoga bermanfaat kurang dan lebihnya mohon maaf, jangan lupa share artikel ini ke teman anda semoga bermanfaat.

Membuat VideoCall dengan Api Bistri

Assalamualaikum Wr. Wb. Selamat Siang semuanya kali ini kita akan membuat VideoCall dengan menggunakan Api Bistri, dengan Api ini kita tidak usah bersusah-susah membuat engine videocall dari awal seperti postingan sebelumnya baca:cara mengakses kamera webcam dari web dengan javascript karena Api ini siap pakai. Untuk menggunakan Api ini anda harus registrasi dulu di api.developers.bistri.com/signup kemudian setelah terdaftar sekarang buat aplikasi baru, klik di menu applications->create new application

selanjunya masukan nama aplikasi anda lalu klik create new key
kunci aplikasi akan dikirimkan ke email anda, buka email anda untuk melihat appId & appKey

Selanjutnya setelah mendapatkan appId & appKey masukan pada script ini


<html>
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <title></title>
 <script type="text/javascript" src="https://api.bistri.com/bistri.conference.min.js"></script>

 <script type="text/javascript">
  /*
    JS library reference:
    http://developers.bistri.com/webrtc-sdk/js-library-reference
*/

var room;
var members;
var localStream;

// when Bistri API client is ready, function
// "onBistriConferenceReady" is invoked
onBistriConferenceReady = function () {

    // test if the browser is WebRTC compatible
    if ( !bc.isCompatible() ) {
        // if the browser is not compatible, display an alert
        alert( "your browser is not WebRTC compatible !" );
        // then stop the script execution
        return;
    }

    // initialize API client with application keys
    // if you don't have your own, you can get them at:
    // https://api.developers.bistri.com/login
    bc.init( {
        "appId": "Maukan AppId disini",
        "appKey": "Masukan App Key disini"
    } );
   
    /* Set events handler */

    // when local user is connected to the server
    bc.signaling.bind( "onConnected", function () {
        // show pane with id "pane_1"
        showPanel( "pane_1" );
    } );

    // when an error occured on the server side
    bc.signaling.bind( "onError", function ( error ) {
        // display an alert message
        alert( error.text + " (" + error.code + ")" );
    } );

    // when the user has joined a room
    bc.signaling.bind( "onJoinedRoom", function ( data ) {
        // set the current room name
        room = data.room;
        members = data.members;
        // ask the user to access to his webcam
        bc.startStream( "webcam-sd", function( stream ){
            // affect stream to "localStream" var
            localStream = stream;
            // when webcam access has been granted
            // show pane with id "pane_2"
            showPanel( "pane_2" );
            // insert the local webcam stream into div#video_container node
            bc.attachStream( stream, q( "#video_container" ), { mirror: true } );
            // then, for every single members present in the room ...
            for ( var i=0, max=members.length; i<max; i++ ) {
                // ... request a call
                bc.call( members[ i ].id, room, { "stream": stream } );
            }
        } );
    } );

    // when an error occurred while trying to join a room
    bc.signaling.bind( "onJoinRoomError", function ( error ) {
        // display an alert message
       alert( error.text + " (" + error.code + ")" );
    } );
   
    // when the local user has quitted the room
    bc.signaling.bind( "onQuittedRoom", function( room ) {
        // stop the local stream
        bc.stopStream( localStream, function(){
            // remove the stream from the page
            bc.detachStream( localStream );
            // show pane with id "pane_1"
            showPanel( "pane_1" );
        } );
    } );
   
    // when a new remote stream is received
    bc.streams.bind( "onStreamAdded", function ( remoteStream ) {
        // insert the new remote stream into div#video_container node
        bc.attachStream( remoteStream, q( "#video_container_2" ) );
    } );
   
    // when a remote stream has been stopped
    bc.streams.bind( "onStreamClosed", function ( stream ) {
        // remove the stream from the page
        bc.detachStream( stream );
    } );
   
    // when a local stream cannot be retrieved
    bc.streams.bind( "onStreamError", function( error ){ 
        switch( error.name ){
            case "PermissionDeniedError":
                alert( "Webcam access has not been allowed" );
                bc.quitRoom( room );
                break
            case "DevicesNotFoundError":
                if( confirm( "No webcam/mic found on this machine. Process call anyway ?" ) ){
                    // show pane with id "pane_2"
                    showPanel( "pane_2" );
                    for ( var i=0, max=members.length; i<max; i++ ) {
                        // ... request a call
                        bc.call( members[ i ].id, room );
                    }
                }
                else{
                    bc.quitRoom( room ); 
                }
                break
        }
    } );

    // bind function "joinConference" to button "Join Conference Room"
    q( "#join" ).addEventListener( "click", joinConference );
   
    // bind function "quitConference" to button "Quit Conference Room"
    q( "#quit" ).addEventListener( "click", quitConference );
   
    // open a new session on the server
    bc.connect();
}

// when button "Join Conference Room" has been clicked
function joinConference(){
    var roomToJoin = "vineet";
    // if "Conference Name" field is not empty ...
    if( roomToJoin ){
        // ... join the room
        bc.joinRoom( roomToJoin );
    }
    else{
        // otherwise, display an alert
        alert( "you must enter a room name !" )
    } 
}

// when button "Quit Conference Room" has been clicked
function quitConference(){
    // quit the current conference room
    bc.quitRoom( room );
}

function showPanel( id ){
    var panes = document.querySelectorAll( ".pane" );
    // for all nodes matching the query ".pane"
    for( var i=0, max=panes.length; i<max; i++ ){
        // hide all nodes except the one to show
        panes[ i ].style.display = panes[ i ].id == id ? "block" : "none";
    };
}

function q( query ){
    // return the DOM node matching the query
    return document.querySelector( query );
}
 </script>
 <style type="text/css">
   #video_container{
      
                margin: 20px;
                text-align: center;
                width:100px;
                height:50px;
                position:absolute;
                top:150px;
                left: 150px;
                z-index: 1;
   }
            #video_container_2{
               
                margin: 20px;
                text-align: center;
                width:800px;
                height:800px;
                position:absolute;
                top:250px;
                left: 200px;
            }
           
   video {
       width: 100%;
   }
            body{
            background-color:#E6E6FA;
            }         
            .container-fluid{
            background-image: linear-gradient(90deg, #4b6cb7, #182848);
            }


 </style>
</head>
<body>
    <div class="container-fluid" style="height:100px ">
            <div>
                <h1 class="col-sm-12 col-lg-9" style="top:25%"><strong><em>Video Call</strong></em></h1>
            </div>
            <div class="col-sm-12 col-lg-3" style="position:relative; top:25%; right:5%;"></div>
     </div>
    <div class="pane" id="pane_1" style="display: block">

        <br>
        <div class="container"><input type="button" value="Make Video Call" id="join" class="btn btn-lg btn-success"></div>
       
    </div>
   
    <div class=" pane" id="pane_2" style="display: none">
        <div id="video_container"></div>
        <div id="video_container_2"></div>
        <input type="button" value="Quit Conference Room" id="quit" class="btn btn-danger btn-default btn-block">
    </div>
</body>
</html>

Selanjutnya tes di browser, jika berhasil melakukan video call hasilnya seperti ini:


Ok sekianlah tutorial kali ini selamat mencoba, jika ada yang ditanyakan silakan kirimkan pertanyaan anda pada kolom komentar dibawah, jika artikel ini bermanfaat silakan di share