Code Example

Kotlin Android Realm MultiProcess Snippets

A step by step Android Realm MultiProcess example.

1. Realm MultiProcess

This is a Realm MultiProcess Example project.

For a full example project follow the following steps

Step 1. Design Layouts

We need to design our XML layouts as follows:

(a). activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start_remote_service"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="onStartButton"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/button"/>
</RelativeLayout>

Step 2. Write Code

Finally we need to write our code as follows:

(a). ProcessInfo.java


package io.realm.examples.realmmultiprocessexample.models;

import java.util.Date;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;

public class ProcessInfo extends RealmObject {
    @PrimaryKey
    private String name;
    private int pid;
    @Required
    private Date lastResponseDate;

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getLastResponseDate() {
        return lastResponseDate;
    }

    public void setLastResponseDate(Date lastResponseDate) {
        this.lastResponseDate = lastResponseDate;
    }
}

(b). Utils.java


package io.realm.examples.realmmultiprocessexample;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.os.Process;

import java.util.Date;
import java.util.List;

import io.realm.examples.realmmultiprocessexample.models.ProcessInfo;

public class Utils {

    public static String getMyProcessName(Context context) {
        String processName = "";
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> infoList = am.getRunningAppProcesses();
        if (infoList == null) {
            throw new RuntimeException("getRunningAppProcesses() returns 'null'.");
        }
        for (RunningAppProcessInfo info : infoList) {
            try {
                if (info.pid == Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            } catch (Exception ignored) {
            }
        }
        return processName;
    }

    public static ProcessInfo createStandaloneProcessInfo(Context context) {
        ProcessInfo processInfo = new ProcessInfo();
        processInfo.setName(getMyProcessName(context));
        processInfo.setPid(android.os.Process.myPid());
        processInfo.setLastResponseDate(new Date());

        return processInfo;
    }
}

(c). MyApplication.java


package io.realm.examples.realmmultiprocessexample;

import android.app.Application;

import io.realm.Realm;
import io.realm.RealmConfiguration;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration configuration = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
        Realm.setDefaultConfiguration(configuration);
    }
}

(d). AnotherProcessService.java


package io.realm.examples.realmmultiprocessexample;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import io.realm.Realm;

public class AnotherProcessService extends Service {

    Handler handler;

    @Override
    public void onCreate() {
        super.onCreate();

        handler = new Handler(Looper.myLooper());
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(Utils.createStandaloneProcessInfo(AnotherProcessService.this));
                realm.commitTransaction();
                realm.close();
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

(e). MainActivity.java


package io.realm.examples.realmmultiprocessexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import io.realm.examples.realmmultiprocessexample.models.ProcessInfo;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private Realm realm;
    private RealmResults<ProcessInfo> processInfoResults;
    private DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);

    private RealmChangeListener<RealmResults<ProcessInfo>> listener =
            new RealmChangeListener<RealmResults<ProcessInfo>>() {
        @Override
        public void onChange(RealmResults<ProcessInfo> results) {
            StringBuilder stringBuilder = new StringBuilder();

            for (ProcessInfo processInfo : results) {
                stringBuilder.append(processInfo.getName());
                stringBuilder.append("npid: ");
                stringBuilder.append(processInfo.getPid());
                stringBuilder.append("nlast response time: ");
                stringBuilder.append(dateFormat.format(processInfo.getLastResponseDate()));
                stringBuilder.append("n------n");
            }
            textView.setText(stringBuilder.toString());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);

        if (realm == null) {
            realm = Realm.getDefaultInstance();
            processInfoResults = realm.where(ProcessInfo.class).findAllAsync();
            processInfoResults.addChangeListener(listener);
        }

        realm.beginTransaction();
        realm.copyToRealmOrUpdate(Utils.createStandaloneProcessInfo(this));
        realm.commitTransaction();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (realm != null) {
            realm.close();
            realm = null;
            processInfoResults = null;
        }
    }

    public void onStartButton(View button) {
        Intent intent = new Intent(MainActivity.this, AnotherProcessService.class);
        startService(intent);
        button.setEnabled(false);
    }
}

Reference

You can [DOWNLOAD FULL CODE](https://github.com/Realm MultiProcess/archive/refs/heads/master.zip).
You can also browse code or read more [here](https://github.com/Realm MultiProcess).
Follow code author here.


Read More.

Related Posts