java - Whatsapp 意图
问题描述
如何在特定时间从我的应用程序自动向某个号码发送 whatsapp 消息?有安卓意图吗?
字符串 toNumber="91XXXXXXXXXX";
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ toNumber +"&text=" + URLEncoder.encode(whatsAppMessage, "UTF-8");
intent.putExtra(Intent.EXTRA_TEXT, whatsAppMessage);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, whatsAppImage);
intent.setType("image/jpeg");
intent.setPackage("com.whatsapp");
intent.setData(Uri.parse(url));
if(Calendar.HOUR==10){
startActivity(intent);
}
}
catch (Exception e){
e.printStackTrace();
}
解决方案
所以,你的问题实际上是关于如何在特定时间执行一些代码,而不是关于 whatsapp?
简单的答案是启动一个计时器,让它每秒触发一次,检查计时器代码中的当前时间。如果时间是 22:00:00 (10PM) 或 10:00:00 (10AM),请调用您的函数。
您不想只检查 Calendar.HOUR==10,因为该小时的每一秒都是如此,因此,您发送的消息可能比您想要的多得多。
请记住,这只会在应用程序正在运行时发生,并且可能仅在它运行在前台时发生。如果您需要一天 24 小时都这样,那么您可能想要创建某种类型的系统服务并让它发送消息。
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// ensures we're using the same current time
Calendar cal2 = cal;
// Set time of calendar to 22:00:00.000
cal.set(Calendar.HOUR_OF_DAY, 22);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after or before 22:00:00.000 today
if ((cal2.after(cal)) || (cal2.before(cal)) {
return;
}
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ toNumber +"&text=" + URLEncoder.encode(whatsAppMessage, "UTF-8");
intent.putExtra(Intent.EXTRA_TEXT, whatsAppMessage);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, whatsAppImage);
intent.setType("image/jpeg");
intent.setPackage("com.whatsapp");
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e){
e.printStackTrace();
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
推荐阅读
- python - Python 的问题:使用 round() 函数时,“TypeError: 'str' object not callable”,值是 FLOAT 变量
- javascript - 如何使用 chrome 扩展将 youtube 视频限制为特定质量
- java - java - 如何在容器中安装java,同时在Dockerfile中编写它?
- flutter - 如何防止 IndexedStack 中的子项被重建?
- python - 如何在 Python 中检查哪个字符串是最近的日历日期
- r - 在 R 中使用 dplyr 根据天数分离降雨时间序列
- html - 带有底部直线响应问题的长电子邮件地址
- java - 当两个相等的字符相邻时,如何解释 Java 中字符串的 split()
- java - InstanceAlreadyExistsException:jetbrains.exodus.entitystore:type=EntityStoreConfig
- python - 在 Windows 上的 python 中按下按键时捕获设备 ID