假设我的应用具有以下要求:
这是我的代码(不相关的部分被省略了)。
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private EditText edtUsername;
private EditText edtPassword;
private Button btnLogin;
// store username & password in SQLite db
// taken from https://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
SessionManager session;
// manage stored items in SQLite
private DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinner.setAdapter(adapter);
db = new DatabaseHelper(this);
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()){
IntentIntegrator scanIntegrator = new IntentIntegrator(LoginActivity.this);
scanIntegrator.setOrientationLocked(false);
scanIntegrator.initiateScan();
}
edtUsername = (EditText) findViewById(R.id.edtName);
edtPassword = (EditText) findViewById(R.id.edtPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null){
String scanContent = scanningResult.getContents();
String[] data = parseContent(scanContent);
db.insertItem(new Item(data[0], data[1], data[2]));
Intent iii = new Intent(LoginActivity.this, ScanResultActivity.class);
startActivity(iii);
}
}
}
ScanResultActivity.java
public class ScanResultActivity extends AppCompatActivity {
private RecyclerView recView;
private ItemAdapter mAdapter;
private DatabaseHelper db;
private List<Item> itemList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
recView = (RecyclerView) findViewById(R.id.recycler_view);
itemList = new ArrayList<>();
db = new DatabaseHelper(this);
itemList.addAll(db.getAllItems());
mAdapter = new ItemAdapter(this, itemList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recView.setLayoutManager(mLayoutManager);
recView.setItemAnimator(new DefaultItemAnimator());
recView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recView.setAdapter(mAdapter);
}
}
第1-3部分运行良好。唯一的问题是一旦您进入4,然后按返回按钮,您将跳至其“非登录状态”的登录活动,因此您必须重复登录过程。相反,我想要的是再次运行QR码扫描部分。该怎么做?
答案 0 :(得分:1)
您可以隔离登录屏幕。除了两个活动,您还可以拥有三个:LoginActivity
-> QRCodeScanActivity
-> ScanResultActivity
。
这样,如果用户按下“后退”按钮,他将返回到QRCodeScanActivity
。
答案 1 :(得分:0)
在onBackPressed();
方法中,只需调用finesh()
方法,您将回到QRCodeScanActivity