首页 > 解决方案 > 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();
    }

标签: javaandroid

解决方案


所以,你的问题实际上是关于如何在特定时间执行一些代码,而不是关于 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);

推荐阅读