我想在警报响起android时显示toast消息

时间:2012-01-27 04:55:04

标签: android notifications alarmmanager alarm

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

谢谢并尊重 Sarfaraz

1 个答案:

答案 0 :(得分:0)

我给你举一个例子,它会每30秒设置一次警报,当警报响起时,将显示警报,当警报设置时,将按下通知。如果我在评论后误解了你的问题,那么我可以删除这个答案以避免联合国必要的帖子。

第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);

}

}

第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);
}
}

步骤4 NotificationService.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运行项目