main.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from kivy.app import App
  2. from kivy.uix.boxlayout import BoxLayout
  3. from kivy.uix.label import Label
  4. from kivy.uix.button import Button
  5. from kivy.clock import Clock
  6. import mysql.connector
  7. # 调用Android的API
  8. SmsManager = autoclass('android.telephony.SmsManager')
  9. PythonActivity = autoclass('org.kivy.android.PythonActivity')
  10. activity = PythonActivity.mActivity
  11. # MySQL数据库连接配置
  12. db_config = {
  13. 'host': 'your_mysql_host', # 例如 'localhost' 或 '192.168.1.100'
  14. 'user': 'your_mysql_user', # 例如 'root'
  15. 'password': 'your_mysql_password', # 例如 'password'
  16. 'database': 'your_database_name', # 例如 'sms_db'
  17. }
  18. # 获取数据库连接
  19. def get_db_connection():
  20. return mysql.connector.connect(**db_config)
  21. # 从MySQL数据库获取数据
  22. def get_data_from_db():
  23. conn = get_db_connection()
  24. cursor = conn.cursor()
  25. cursor.execute("SELECT phone_number, message FROM messages WHERE sent = 0")
  26. data = cursor.fetchall()
  27. cursor.close()
  28. conn.close()
  29. return data
  30. # 更新数据库状态
  31. def update_db_status(phone_number):
  32. conn = get_db_connection()
  33. cursor = conn.cursor()
  34. cursor.execute("UPDATE messages SET sent = 1 WHERE phone_number = %s", (phone_number,))
  35. conn.commit()
  36. cursor.close()
  37. conn.close()
  38. # 发送短信
  39. def send_sms(phone_number, message):
  40. sms_manager = SmsManager.getDefault()
  41. sms_manager.sendTextMessage(phone_number, None, message, None, None)
  42. class SmsApp(App):
  43. def build(self):
  44. self.layout = BoxLayout(orientation='vertical')
  45. self.label = Label(text="SMS Sender")
  46. self.layout.add_widget(self.label)
  47. self.start_button = Button(text="Start Sending SMS")
  48. self.start_button.bind(on_press=self.start_sending)
  49. self.layout.add_widget(self.start_button)
  50. return self.layout
  51. def start_sending(self, instance):
  52. self.label.text = "Started SMS Sending Service..."
  53. # 每10秒调用一次 send_sms_loop
  54. Clock.schedule_interval(self.send_sms_loop, 10) # 10秒间隔
  55. def send_sms_loop(self, dt):
  56. data = get_data_from_db()
  57. if data:
  58. for phone_number, message in data:
  59. try:
  60. send_sms(phone_number, message)
  61. update_db_status(phone_number)
  62. self.label.text = f"SMS sent to {phone_number}"
  63. except Exception as e:
  64. self.label.text = f"Failed to send SMS: {e}"
  65. else:
  66. self.label.text = "No more messages to send"
  67. if __name__ == '__main__':
  68. SmsApp().run()