vendredi 8 mars 2019

Generate Random Characters in Android Studio using Broadcast

Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout

The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.

AndroidManifest.xml:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".RandomCharacterService"></service>

    </application>

MainActivityjava:

    package com.example.cs7455rehmarazzaklab8;

    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.IBinder;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.support.constraint.ConstraintLayout;
    import android.support.v4.content.LocalBroadcastManager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.Window;
    import android.widget.Button;
    import android.widget.Toast;
    import java.util.Random;

    public class MainActivity extends AppCompatActivity
    {
        private Button btnStart, btnStop;
        private EditText myTV;

        private Intent serviceIntent;
        private RandomCharacterService myService;
        private ServiceConnection myServiceConnection;
        private boolean isServiceOn; //checks if the service is on

        private int myRandomCharacter;
        char MyRandomCharacter = (char)myRandomCharacter;
        private boolean isRandomGeneratorOn;

        private final int MIN = 65;
        char m = (char)MIN;
        private final int MAX = 26;
        char x = (char)MAX;
        private final String TAG = "Random Char Service: ";

        private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        private Context mContext;
        private Random mRandom = new Random();

        // Initialize a new BroadcastReceiver instance
        private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver() 
    {
            @Override
            public void onReceive(Context context, Intent intent) {
            // Get the received random number
            myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);

            // Display a notification that the broadcast received
            Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();
        }
    };

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

        // Get the application context
        mContext = getApplicationContext();

        btnStart = (Button) findViewById(R.id.StartButton);
        btnStop = (Button) findViewById(R.id.StopButton);


        myTV = (EditText)findViewById(R.id.RandomCharText);

        // Register the local broadcast
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));

        // Set a click listener for send button
        btnStart.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                isServiceOn = true;

                serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
                startService(serviceIntent);
                setRandomNumber();
                // Generate a random char
                myRandomCharacter = new Random().nextInt(x)+m;

                // Initialize a new intent instance
                Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
                // Put the random number to intent to broadcast it
                intent.putExtra("RandomCharacter",myRandomCharacter);

                // Send the broadcast
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

                // Update the TextView with random character
                myTV.setText(" " + myRandomCharacter );
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                isServiceOn = false;

                stopService(serviceIntent);
            }
        });
    }
    private void setRandomNumber()
    {
        myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
        String alphabet = myTV.getText().toString();

    }

}

RandomCharacterService.java:

    package com.example.cs7455rehmarazzaklab8;

    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.support.annotation.IntDef;
    import android.support.annotation.Nullable;
    import android.util.Log;

    import java.util.Random;


    public class RandomCharacterService extends Service
    {
        private int myRandomCharacter;
        char MyRandomCharacter = (char)myRandomCharacter;
        private boolean isRandomGeneratorOn;

        private final int MIN = 65;
        char m = (char)MIN;
        private final int MAX = 26;
        char x = (char)MAX;
        private final String TAG = "Random Char Service: ";

        private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        class RandomCharacterServiceBinder extends Binder{
            public RandomCharacterService getService()
            {
                return RandomCharacterService.this;
            }
        }

    private IBinder myBinder = new RandomCharacterServiceBinder();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
        isRandomGeneratorOn = true;

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                startRandomGenerator();
            }
        }
        ).start();

        return START_STICKY;
    }

    private void startRandomGenerator()
    {
        while(isRandomGeneratorOn)
        {
            char alphabet = 'A';
            for (int i = 65; i < 90; i++)
            {
                try
                {
                    Thread.sleep(1000);
                    if(isRandomGeneratorOn)
                    {
                        alphabet++;
                        myRandomCharacter = new Random().nextInt(x)+m;
                        Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);
                    }
                }
                catch(InterruptedException e)
                {
                    Log.i(TAG, "Thread Interrupted.");
                }

            }

        }

    }

    private void stopRandomGenerator()
    {
        isRandomGeneratorOn = false;
    }

    public int getRandomCharacter()
    {
        return myRandomCharacter;
    }

    public boolean isRandomGeneratorOn() {
        return isRandomGeneratorOn;
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        stopRandomGenerator();
        Log.i(TAG, "Service Destroyed.");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        Log.i(TAG, "In onBind ...");
        return myBinder;
    }
}




Aucun commentaire:

Enregistrer un commentaire