繁体   English   中英

Android Broadcast Receiver作为内部静态类传递字符串

[英]Android Broadcast Receiver as inner static class Passing a String

可能您想跳至Update 2并根据需要检查代码

我正在构建条形码扫描仪,并且难以传递从将BroadcastReceiver扩展为MainActivity类的内部类捕获的数据,我确实了解了静态对象与非静态对象之间的区别,但是我遇到了麻烦。

无法从内部类调用我的逻辑方法。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState){...}

public void Logic(String result){// Do something...}

//Inner Class
   public static class ScanResultReceiver extends BroadcastReceiver {
   @Override
    public void onReceive(Context context, Intent intent) {...
      // data here captured fine! 
     // Here I want to send my data to MainActivity Logic(result)
     Logic(result);
    }
 }

如果将“ Logic()”作为静态方法,则从Toaster / variables..etc的静态方法中调用非静态方法会遇到很多错误

更新资料

这个方法在MainActivity内部,我想从内部类中调用它

public  void Logic(String result) throws Exception {
            //prepare the results
            if (mDecodeResult.decodeValue.substring(0, 1).equals("{") && mDecodeResult.decodeValue.substring(mDecodeResult.decodeValue.length() - 1).equals("}")) {
                if (!(mDecodeResult.decodeValue.equals("SCAN AGAIN"))) {
                    mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(1);
                    mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(0, mDecodeResult.decodeValue.length() - 1);
                }
            }
            if (mDecodeResult.decodeValue.equals("SCAN AGAIN")) {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "No scan data received! Please Scan Again", Toast.LENGTH_SHORT);
                toast.show();
            } else if (mDecodeResult.decodeValue != null && tourFlag) {
                String formattedDate = getTime();
                String scanContent = mDecodeResult.decodeValue;
                boolean found = false;
                if (ForcedOrRandom.equals("Random")) {
                    String[] b;
                    for (String l : ToBeScanned) {
                        b = l.split(":");
                        if (scanContent.equals(b[0])) {
                            Log.d("remove", "scanned: " + scanContent);
                            Log.d("remove", "remove : " + b[0]);
                            found = true;
                        }
                    }
                } else if (ForcedOrRandom.equals("Forced")) {
                    String[] b;
                    for (String I : FTobeScannedNext) {
                        b = I.split(":");
                        if (scanContent.equals(b[0])) {
                            Log.d("remove", "scanned: " + scanContent);
                            Log.d("remove", "remove : " + b[0]);
                            found = true;
                        }
                    }
                }// end Skip/Forced
                if (listLoaded && found) {
                    theResult[resultCount].setTourID(currentTourId);
                    theResult[resultCount].setBarcode(scanContent);
                    BarcodeObject a = getBarcodeInfo(scanContent);
                    if (ForcedOrRandom.equals("Random")) {
                    } else {
                        if (myTimer != null) {
                            myTimer.cancel();
                            Timer = (TextView) findViewById(R.id.timertext);
                            Timer.setText("");
                            PlayOrPause.setVisibility(View.INVISIBLE);
                        }
                        boolean isTimed = a.getForceNextBarCode().equals("");
                        if (!(isTimed)) {
                            PlayOrPause = (ImageButton) findViewById(R.id.PlayPause);
                            PlayOrPause.setVisibility(View.VISIBLE);
                            PlayOrPause.setImageResource(R.drawable.pause);
                            final AlertDialog.Builder timealert = new AlertDialog.Builder(this);
                            PlayOrPause.setEnabled(true);
                            long duration = Integer.parseInt(a.getForceNextBarCode());
                            duration = duration * 60000;
                            myTimer = new CountDownTimer(duration, 1000) {
                                @Override
                                public void onTick(long millisuntilFinished) {
                                    int seconds = (int) (millisuntilFinished / 1000) % 60;
                                    int minutes = (int) ((millisuntilFinished / (1000 * 60)) % 60);
                                    Timer = (TextView) findViewById(R.id.timertext);
                                    Timer.setText(minutes + ":" + seconds);
                                    timeLeft = millisuntilFinished;
                                }

                                String value = "";

                                @Override
                                public void onFinish() {
                                    Timer = (TextView) findViewById(R.id.timertext);
                                    theResult[resultCount].setScanstatus(scanStatusTimeElapsed);
                                    timealert.setTitle("Site Secure");
                                    timealert.setMessage("Time Elapsed! Enter reason");
// Set an EditText view to get user input
                                    final EditText input = new EditText(MainActivity.this);
                                    timealert.setView(input);
                                    timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            value = input.getText().toString();
                                            // Do something with value!
                                            while (value.equals("")) {
                                                timealert.setView(input);
                                                timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int whichButton) {
                                                        value = input.getText().toString();
                                                    }
                                                });
                                            }
                                            theResult[resultCount].setComments(value);
                                        }
                                    });
                                    timealert.setIcon(android.R.drawable.ic_dialog_alert);
                                    timealert.show();
                                    Timer.setText(R.string.Time_Elapsed);
                                }
                            };
                            myTimer.start();
                        }
                    }

                    theResult[resultCount].setBarcodeID(a.getBarCodeId());
                    theResult[resultCount].setDateScanned(formattedDate);
                    theResult[resultCount].setSkipped(getResources().getString(R.string.Scanned));

                }// end big if listLoaded && found
                contentTxt.setText(scanContent);
                Toaster(getResources().getString(R.string.TScan_Complete));
                if (mainScanCounter == 0) {
                    if (tourDecider(scanContent)) {//tour decider is called to determine if this is boolJanamScanner random or forced tour
                        tourId = scanContent;
                        if (!(readFileOffline(siteSecurePath + "/doneTourNumber.txt").equals(""))) {
                            SYNC.setEnabled(true);
                        }
                    }
                } else if (mainScanCounter > 0) {
                    if (ForcedOrRandom.equals("Random")) {
                        ListManager(scanContent);
                    } else {
                        ForcedListManager(scanContent);
                    }
                }
            } else if (mDecodeResult.decodeValue != null && officerScanFlag) {
                TextView officertextview = (TextView) findViewById(R.id.officerid);
                UserObject theofficer = getUserInfo(mDecodeResult.decodeValue);
                if (theofficer == null) {
                    popUps("Error", "Invalid Officer ID, Please Rescan", "TITLE");
                    officerScan.setEnabled(true);
                } else if (theofficer != null) {
                    // officer ID found need to store it for backup
                    officerId = theofficer.getOfficerid();
                    makeFileOffline(officerId, "officerID");
                    officertextview.setText(theofficer.getUsername());
                    officerScanFlag = false;
                    startTimersOfficerID = getTime();
                    tourBtn.setEnabled(true);
                }
            }
            if (mDecodeResult.decodeValue != null && exceptionFlag) {
                Log.d("check", "exception was clicked");
                String ex_result = mDecodeResult.decodeValue;
                for (int i = 0; i < theExceptions.length; i++) {
                    if (!(theExceptions[i].getBarcode().equals(ex_result))) {
                        String refnum = theExceptions[i].getRefNum();
                        i = theExceptions.length;
                        theResult[resultCount - 1].setException(refnum);
                    }
                }
                exceptionFlag = false;
                Toaster(getResources().getString(R.string.TScan_Complete));
            }
    }    // Logic Ends

更新2

不知道是否需要其他线程,但是我将找到的内容放到了下面,我的问题缩小到以下范围:

我正在等待一个意向

<action android:name="device.scanner.USERMSG" />

经许可

android:permission="com.permission.SCANNER_RESULT_RECEIVER"

现在我的问题

如果用户点击按钮并在不到0.5秒的onKeyup()释放onKeyup()事件,则会在扩展了BroadcastReceiver的静态类内部的onReceive()之前触发onKeyup() ,这会引起问题,因为在更新该类之前会调用Logic() onReceive()字符串

如果用户按住按钮足够长的时间,则onReceive将被调用,一切都会变得很好。

如何确保始终首先调用onReceive()?

 public boolean onKeyUp(int keycode, KeyEvent event) {

        if (keycode == 221 || keycode == 220 || keycode == 222) {
                    Logic(result);     
}
    return true;
    }

移动以下代码行:

public void Logic(String result){// Do something...}

在您的class ScanResultReceiver ,它肯定可以工作。 您的代码应如下所示:

public static class ScanResultReceiver extends BroadcastReceiver {
   public ScanResultReceiver() {
          //empty constructor
   }

   @Override
    public void onReceive(Context context, Intent intent) {...
      // data here captured fine! 
     // Here I want to send my data to MainActivity Logic(result)
     Logic(result);
    }

    public void Logic(String result){/* ... */}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM