package com.example.app1; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import java.util.List; public class MainActivity2 extends AppCompatActivity { private EditText username; private EditText password; private Button login; private Button startServiceButton; private boolean isServiceRunning = false; private DBHelper dbHelper; // 数据库助手类 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_login); username = findViewById(R.id.username); password = findViewById(R.id.password); login = findViewById(R.id.login); startServiceButton = findViewById(R.id.btnStartService); // 创建通知渠道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } startServiceButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isServiceRunning) { startMyService(); isServiceRunning = true; } } }); dbHelper = new DBHelper(MainActivity2.this); // 初始化数据库助手类 login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String strUsername = username.getText().toString().trim(); String strPassword = password.getText().toString().trim(); // 获取所有用户数据 List userList = dbHelper.getAllUsers(); // 检查是否有用户数据 if (!userList.isEmpty()) { // 遍历用户数据列表 for (User user : userList) { String savedUsername = user.getUsername(); String savedPassword = user.getPassword(); // 检查用户名和密码是否匹配 if (strUsername.equals(savedUsername) && strPassword.equals(savedPassword)) { Toast.makeText(MainActivity2.this, "恭喜,登录成功!", Toast.LENGTH_SHORT).show(); Intent intent1 = new Intent(MainActivity2.this, IndexActivity.class); startActivity(intent1); return; // 如果匹配成功,则直接返回,不再继续循环 } } // 如果循环结束仍未匹配成功,则提示用户名或密码错误 Toast.makeText(MainActivity2.this, "用户名或密码错误!", Toast.LENGTH_SHORT).show(); } else { // 如果用户数据列表为空,则提示用户名或密码错误 Toast.makeText(MainActivity2.this, "用户名或密码错误!", Toast.LENGTH_SHORT).show(); } } }); } private void startMyService() { Intent serviceIntent = new Intent(this, MyService.class); startService(serviceIntent); } //点击注册按钮时,跳转到注册界面 public void zhuce(View view) { Intent intent2 = new Intent(MainActivity2.this, MainActivity3.class); startActivity(intent2); } }