应用程序关闭时运行警报

时间:2015-11-03 12:08:02

标签: android broadcastreceiver alarmmanager

我正在创建一个也具有警报功能的应用程序。它的效果和我期望的一样。但只有在应用程序正在运行时。如果我使用任务管理器关闭应用程序,则警报永远不会响这是否意味着我必须创建服务?我已经读过,如果您使用带有BroadCast Receiver的Alarm Manager,即使应用程序没有在手机中运行,也不需要服务。如果我错了,请纠正我。

MainActivity

public class MainActivity extends Activity {
private AlarmManager manager;
private PendingIntent intent;
private AlarmManagerHelper alarm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    alarm=new AlarmManagerHelper();
}

@Override
protected void onStart() {
    super.onStart();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void startRepeatingTimer(View view) {
    Context context = this.getApplicationContext();
    if(alarm != null){
        alarm.setAlarms(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){

    Toast.makeText(this,"hello one time",Toast.LENGTH_SHORT).show();
    Context context = this.getApplicationContext();
    if(alarm != null){
        alarm.setOnetimeTimer(context);
    }else{
        Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
    }
}




}

AlarmManager.java

public class AlarmManagerHelper extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
@Override
public void onReceive(Context context, Intent intent) {

    PowerManager manager = (PowerManager)     context.getSystemService(context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"mylock");
    wakeLock.acquire();

    Bundle extra = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();

    if(extra!=null && extra.getBoolean(ONE_TIME, Boolean.FALSE)){
        msgStr.append("One time Timer : ");
    }

    Format formatter = new SimpleDateFormat("hh:mm:ss");
    msgStr.append(formatter.format(new Date()));
    Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show(); 











    //Release the lock
   wakeLock.release();




}

public void  setAlarms(Context context) {

    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context,AlarmManagerHelper.class);
    intent.putExtra(ONE_TIME,Boolean.FALSE);
    PendingIntent it = PendingIntent.getBroadcast(context,0,intent,0);
    manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 1000 * 5 , it);

}

public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, AlarmManagerHelper.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 manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context,AlarmManagerHelper.class);
    intent.putExtra(ONE_TIME,Boolean.TRUE);
    PendingIntent it = PendingIntent.getBroadcast(context,0,intent,0);
    manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, it);
}

}

的AndroidManifest.xml

<receiver android:name="com.example.randomlocks.alarmdemo.AlarmManagerHelper"></receiver>

1 个答案:

答案 0 :(得分:0)

接收者

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        //此处可以添加闹钟铃声
        System.out.println("我是闹钟,我要叫醒你...");
        Toast.makeText(arg0, "我是闹钟,我要叫醒你...", Toast.LENGTH_SHORT).show();
    }
}

活动

package com.example.alarmmanager;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity implements OnClickListener {

    private AlarmManager alarmManager;
    private PendingIntent operation;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化按钮,并绑定监听事件
        findViewById(R.id.clock).setOnClickListener(this);
        findViewById(R.id.repeating_clock).setOnClickListener(this);
        findViewById(R.id.cancel_clock).setOnClickListener(this);

        // 获取AlarmManager对象
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        // 创建Intent对象,action为android.intent.action.ALARM_RECEIVER
        Intent intent = new Intent("android.intent.action.ALARM_RECEIVER");
        operation = PendingIntent.getBroadcast(this, 0, intent, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
           case R.id.clock:// 设置一次性闹钟
                   alarmManager.set(AlarmManager.RTC_WAKEUP, 10000, operation);
                   break;
           case R.id.repeating_clock:// 设置重复闹钟
                   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 10000,
                                operation);
                   break;
           case R.id.cancel_clock:// 取消闹钟
                   alarmManager.cancel(operation);
                   break;
           default:
                   break;
        }
    }
}

xml文件

<LinearLayout 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:orientation="vertical" >

    <Button
        android:id="@+id/clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置一次性闹钟" />

    <Button
        android:id="@+id/repeating_clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置重复闹钟" />

    <Button
        android:id="@+id/cancel_clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="取消闹钟" />

</LinearLayout>