簡體   English   中英

使用廣播在Android Studio中生成隨機字符

[英]Generate Random Characters in Android Studio using Broadcast

正在開發應該通過廣播生成隨機字符的應用程序。 我需要廣播由自定義服務生成的隨機字符,以便注冊用來攔截廣播的主要活動可以獲取隨機數並將其顯示在EditText上。 布局如下所示: 應用布局

開始按鈕將觸發隨機字符生成器服務。 EditText將顯示實時生成的隨機數(無需按任何按鈕)。 停止按鈕將停止服務。 EditText將不顯示任何數字。 我已經創建了一個服務(RandomCharacterService)並將其注冊在清單中。 運行該應用程序后,我的應用程序崩潰了。 我確定是因為我沒有在清單中注冊廣播,但是我不知道該怎么做。 我在主要活動中如何處理廣播可能出了點問題。 在開始按鈕的按鈕單擊方法中,我嘗試執行一個for循環,但這也導致應用程序崩潰。

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 start 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 character 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;
    }
}

調用堆棧: 運行應用程序的調用堆棧

從嘗試按停止按鈕調用堆棧:從嘗試按停止按鈕崩潰

由於您正在使用綁定服務(使用Ibinder)。 您將必須通過調用bindService而不是startService來啟動服務。 但是在此之前,您需要初始化ServiceConnection變量,並更好地使用isServiceOn布爾值,如以下示例所示。

private ServiceConnection myServiceConnection = new ServiceConnection() {
    @Override
    // IBinder interface is through which we receive the service object for communication.
    public void onServiceConnected(ComponentName name, IBinder binder) {
        RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
        isServiceOn = true;
        myService = myBinder.getService();
        Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        isServiceOn = false;
        myService = null;
    }
};

調用onServiceConnected之后,您將獲得服務對象。 在執行點擊之前,很有可能將初始化您的服務。 但是只是為了確保您可以在其中敬酒一些消息。

而且,您應該使用Activity的onCreate方法啟動該服務,以便該服務在創建時會花費一些時間。 因此,將下面的代碼從單擊偵聽器的位置移到onCreate方法。

serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
// startService(serviceIntent); <-- remove this line, call bindService
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);

並等待服務連接Toast出現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM