【问题标题】:android activity comes to foreground after alarm manager警报管理器后android活动进入前台
【发布时间】:2012-12-21 19:54:29
【问题描述】:

我有应用程序,它在警报管理器中生成事件,并在特定时间调用它。 代码如下所示

Intent intent = new Intent(this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(this,req_code, intent, PendingIntent.FLAG_CANCEL_CURRENT);    
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY*7,
                    pendingIntent);

Intent 调用此活动。

public class AlarmActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void onStart(){
        super.onStart();
        //Change ringer mode
        //Add notification in status bar
        //Other booring stuff here...
        Toast.makeText(this,"Finishing",2000).show();
        finish();
    }
}

在无聊的东西中有一些代码应该在后台运行(更改铃声模式)

一切都对我有用,除了一件事。每当警报管理器调用我的活动时 - 应用程序就会进入前台。 只需要在后台更改铃声模式,并在状态栏中添加通知。

有什么办法不让应用程序进入前台?

【问题讨论】:

标签: android android-activity alarmmanager foreground


【解决方案1】:

您应该在BroadCastReceiver 中完成所有这些操作。没有 UI,并且有一个 Context 变量传递给 Receiver 的 onReceive() 方法,它允许您基本上执行 Activity 所做的任何事情,而无需实际的 UI。这意味着您可以设置铃声、显示状态栏通知等。 您的 BroadcastReceiver 类应如下所示:

public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Change ringer mode
    //Add notification in status bar
    //Other boring stuff here...
    Toast.makeText(context,"Finishing",2000).show();
    }
}

请注意,对于您的 Toast,使用了名为 context 的变量。

您的AlarmManager 代码应该如下所示:

Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,req_code, intent, PendingIntent.FLAG_CANCEL_CURRENT);    
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY*7,
                    pendingIntent);

你的清单应该有这个:

 <receiver android:name=".AlarmBroadcastReceiver" >
        </receiver>

【讨论】:

  • 我在开始时尝试了广播接收器...出于某种原因 - 它对我不起作用! (警报管理器没有调用它)。尝试了不同的 tuts,有些东西一直不适合我。
  • 别忘了你只有大约 10 秒的时间在广播接收器中工作,之后不能保证它会继续运行。
  • 除非你循环很多,否则他们的代码似乎在 10 秒的时间范围内。
  • 好的,tnx,我要再试一次。 Tnx
【解决方案2】:

将此行添加到您的AndroidManifest 中的Activity

android:theme="@android:style/Theme.NoDisplay"

你有一个没有任何显示的活动。由于您已经在代码中调用了finish();,因此它看起来像是在后台运行。

【讨论】:

  • 在此之后 - 我的应用程序仍然打开...我添加了闹钟,更改为 chrome,当闹钟响起时 - 更改回我的应用程序 :(
  • 只需调用finish();在您的计算或工作完成后在您的应用中。
  • 我已经完成();没有完成();它挂在“空白”屏幕上。
  • 当你有finish()的时候,就说明你的activity已经不存在了,怎么可能。也许根本没有调用finish。
  • 可能在调用finish() 后会打开不同的(默认)活动窗口?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多