我希望 Android 闹钟响起时显示 toast 消息

发布于 2024-12-29 09:26:47 字数 109 浏览 1 评论 0原文

我的问题是,我希望在 Android 闹钟设置为响铃时显示 toast 消息。我有 AnCal 闹钟应用程序。我已经尝试了很多,但它不起作用...我需要你的帮助...

谢谢并尊重 萨法拉兹

My question is, I want toast message to be displayed when alarm is set to rings for android..I have AnCal alarm application ..I have tried a lot but its not working ...I need your help...

Thanks and regard
Sarfaraz

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫以 2025-01-05 09:26:47

我给你一个例子,每 30 秒设置一次闹钟,当闹钟响起时,将会出现 toast,当设置闹钟时,将推送通知。如果我误解了你的问题发表评论,那么我可以删除这个答案以避免不必要的帖子。

步骤 1 MainActivity.java

package com.example.alarmmanager;

import com.example.alarmmanager.NotificationReceiverActivity;
import com.example.alarmmanager.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    alarm = new AlarmManagerBroadcastReceiver();
}
@Override
protected void onStart() {
super.onStart();
}

    public void startRepeatingTimer(View view) {
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.SetAlarm(context);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }

    public void cancelRepeatingTimer(View view){
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.CancelAlarm(context);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }

    public void onetimeTimer(View view){
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.setOnetimeTimer(context);
     createNotification(view);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }
    public void createNotification(View view) {
      /*********** Create notification ***********/

            final NotificationManager mgr=
                (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification note=new Notification(R.drawable.ic_launcher,
                                                            "Android Example Status message!",
                                                            System.currentTimeMillis());

            // This pending intent will open after notification click
            PendingIntent i= PendingIntent.getActivity(this, 0,
                                                    new Intent(this, NotificationReceiverActivity.class),
                                                    0);

            note.setLatestEventInfo(this, "Android Example Notification Title",
                                    "This is the android example notification message", i);

            //After uncomment this line you will see number of notification arrived
            //note.number=2;
            mgr.notify(0, note);

        }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

步骤 2 AlarmManagerBroadcastReceiver.java

package com.example.alarmmanager;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.Toast;  

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver{
final public static String ONE_TIME = "onetime";
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
    //Acquire the lock
    wl.acquire();

    //You can do the processing here update the widget/remote views.
    Bundle extras = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();

    if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
    msgStr.append("One time Timer : ");
    }
    Format formatter = new SimpleDateFormat("hh:mm:ss a");
    msgStr.append(formatter.format(new Date()));

    Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();

    //Release the lock
    wl.release();
    Intent service1 = new Intent(context, NotificationService.class);
    context.startService(service1);
}
public void SetAlarm(Context context)
{
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 30 seconds
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}

public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
 AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);

}

}

步骤 3NotificationReceiverActivity.java

package com.example.alarmmanager;

import android.app.Activity;
import android.os.Bundle;

public class NotificationReceiverActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result);
}
}

步骤 4NotificationService.java // 这是推送通知,如果不需要通知,可以删除它

package com.example.alarmmanager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate()
{
   // TODO Auto-generated method stub 
   super.onCreate();
}

@Override
public void onStart(Intent intent, int startId)
{
    final NotificationManager mgr=
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification note=new Notification(R.drawable.ic_launcher,
                                                        "Android Example Status message!",
                                                        System.currentTimeMillis());

        // This pending intent will open after notification click
        PendingIntent i= PendingIntent.getActivity(this, 0,
                                                new Intent(this, NotificationReceiverActivity.class),
                                                0);

        note.setLatestEventInfo(this, "Android Example Notification Title",
                                "This is the android example notification message", i);

        //After uncomment this line you will see number of notification arrived
        note.number=startId;
        mgr.notify(0, note);
}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
}
}

步骤 5:AndroidManifest.xml

<uses-permission android:name='android.permission.WAKE_LOCK'/>

 <receiver android:name="com.example.alarmmanager.AlarmManagerBroadcastReceiver">  </receiver>
     <service android:name="com.example.alarmmanager.NotificationService"
             android:enabled="true" />

步骤 6 Activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="43dp"
    android:onClick="startRepeatingTimer"
    android:text="Start Alarm repeating 30 sec" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_marginTop="50dp"
    android:layout_toRightOf="@+id/textView1"
    android:onClick="cancelRepeatingTimer"
    android:text="Cancel Alarm" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="58dp"
    android:onClick="onetimeTimer"
    android:text="Start One Time Alarm" />

</RelativeLayout>

步骤7 result.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:text="This is the result activity opened from the notification"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:id="@+id/textView1"></TextView>

</RelativeLayout>

步骤8 运行项目

I am giving you an example that will set alarm every 30 seconds and when the alarm will ring the toast will appear and when alarm will be set notification will be pushed. If I misunderstood your question post comment so i can delete this answer to avoid UN-necessary post.

Step 1 MainActivity.java

package com.example.alarmmanager;

import com.example.alarmmanager.NotificationReceiverActivity;
import com.example.alarmmanager.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    alarm = new AlarmManagerBroadcastReceiver();
}
@Override
protected void onStart() {
super.onStart();
}

    public void startRepeatingTimer(View view) {
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.SetAlarm(context);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }

    public void cancelRepeatingTimer(View view){
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.CancelAlarm(context);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }

    public void onetimeTimer(View view){
     Context context = this.getApplicationContext();
     if(alarm != null){
     alarm.setOnetimeTimer(context);
     createNotification(view);
     }else{
     Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
     }
    }
    public void createNotification(View view) {
      /*********** Create notification ***********/

            final NotificationManager mgr=
                (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification note=new Notification(R.drawable.ic_launcher,
                                                            "Android Example Status message!",
                                                            System.currentTimeMillis());

            // This pending intent will open after notification click
            PendingIntent i= PendingIntent.getActivity(this, 0,
                                                    new Intent(this, NotificationReceiverActivity.class),
                                                    0);

            note.setLatestEventInfo(this, "Android Example Notification Title",
                                    "This is the android example notification message", i);

            //After uncomment this line you will see number of notification arrived
            //note.number=2;
            mgr.notify(0, note);

        }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

Step 2 AlarmManagerBroadcastReceiver.java

package com.example.alarmmanager;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.Toast;  

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver{
final public static String ONE_TIME = "onetime";
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
    //Acquire the lock
    wl.acquire();

    //You can do the processing here update the widget/remote views.
    Bundle extras = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();

    if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
    msgStr.append("One time Timer : ");
    }
    Format formatter = new SimpleDateFormat("hh:mm:ss a");
    msgStr.append(formatter.format(new Date()));

    Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();

    //Release the lock
    wl.release();
    Intent service1 = new Intent(context, NotificationService.class);
    context.startService(service1);
}
public void SetAlarm(Context context)
{
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 30 seconds
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}

public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
 AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);

}

}

Step 3 NotificationReceiverActivity.java

package com.example.alarmmanager;

import android.app.Activity;
import android.os.Bundle;

public class NotificationReceiverActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result);
}
}

Step 4 NotificationService.java // this is to push notification you can remove this if you do not want notifications

package com.example.alarmmanager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate()
{
   // TODO Auto-generated method stub 
   super.onCreate();
}

@Override
public void onStart(Intent intent, int startId)
{
    final NotificationManager mgr=
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification note=new Notification(R.drawable.ic_launcher,
                                                        "Android Example Status message!",
                                                        System.currentTimeMillis());

        // This pending intent will open after notification click
        PendingIntent i= PendingIntent.getActivity(this, 0,
                                                new Intent(this, NotificationReceiverActivity.class),
                                                0);

        note.setLatestEventInfo(this, "Android Example Notification Title",
                                "This is the android example notification message", i);

        //After uncomment this line you will see number of notification arrived
        note.number=startId;
        mgr.notify(0, note);
}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
}
}

Step 5 : AndroidManifest.xml

<uses-permission android:name='android.permission.WAKE_LOCK'/>

 <receiver android:name="com.example.alarmmanager.AlarmManagerBroadcastReceiver">  </receiver>
     <service android:name="com.example.alarmmanager.NotificationService"
             android:enabled="true" />

Step 6 activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="43dp"
    android:onClick="startRepeatingTimer"
    android:text="Start Alarm repeating 30 sec" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_marginTop="50dp"
    android:layout_toRightOf="@+id/textView1"
    android:onClick="cancelRepeatingTimer"
    android:text="Cancel Alarm" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="58dp"
    android:onClick="onetimeTimer"
    android:text="Start One Time Alarm" />

</RelativeLayout>

Step 7 result.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:text="This is the result activity opened from the notification"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:id="@+id/textView1"></TextView>

</RelativeLayout>

Step 8 Run project

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文