从服务启动活动 - 当然 (Android)
我只是尝试从服务中启动一项活动几天。这不可能那么困难!我想要的是:
1)从后台服务启动一个活动(由 AlarmManager 调度)。目前我正在使用此代码执行此操作
Intent i = new Intent(this, MyDialogActivity.class);
i.putExtra(MyDialogActivity.TEXT, myObject.getText());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
2)显示此活动,无论根活动是否在顶部,是否通过后退按钮销毁根活动,是否通过主页按钮暂停根活动
3)显示此活动设备是否处于待机状态(用户将设备从待机状态唤醒后,应显示活动)
4)确定销毁活动,并在用户看到活动并按下按钮(包括主页按钮和后退按钮)后发送广播)。目前我正在使用此代码执行此操作(pm 是 PowerManager)
protected void onPause() {
if (pm.isScreenOn()) {
sendBroadcast(retValue);
if (!isFinishing()) {
finish();
} else {
moveTaskToBack(true);
}
}
super.onPause();
}
5)防止此活动可以从调用服务之外的其他点启动。目前我正在通过在 AndroidManifest 中设置此属性来实现此目的:
android:name=".activities.MyDialogActivity" 机器人:noHistory =“真” android:excludeFromRecents="true"
但无论我在做什么,我都无法实现 2) 和 3)。有人可以帮助我吗?
谢谢你!
I'm trying simply to start an activity from a service for days. This can't be that difficult! All I want is this:
1) Start an Activity from a background service (scheduled by AlarmManager). Currently I'm doing this with this code
Intent i = new Intent(this, MyDialogActivity.class);
i.putExtra(MyDialogActivity.TEXT, myObject.getText());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
2) Show this Activity wheter the root activity is on top, wheter the root activity was destroyed via the back button, wheter the root activity was paused via the home button
3) Show this Activity wheter the device is on standby or not (Activity should be shown after the user wakes up the device from standby)
4) Destroy the activity for sure and send a broadcast after the user saw the activity and pressed a button (including home- and back-button). Currently I'm doing this with this code (pm is PowerManager)
protected void onPause() {
if (pm.isScreenOn()) {
sendBroadcast(retValue);
if (!isFinishing()) {
finish();
} else {
moveTaskToBack(true);
}
}
super.onPause();
}
5) Prevent that this activity could be started from another point than the calling service. Currently I'm doing this with setting this attributes in the AndroidManifest:
android:name=".activities.MyDialogActivity"
android:noHistory="true"
android:excludeFromRecents="true"
But whatever I'm doing, I can't realize 2) and 3). Could anybody help me?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在从服务启动活动时遇到了同样的问题。我试图启动系统语音拨号器。
我的问题是因为我使用应用程序上下文(this.getApplicationContext())而引起的。一旦我改成“这个”,它就起作用了。
这段代码对我有用:
我使用以下方式获取上下文:
I had same issues with starting an activity from a service. I was trying to start the system voice dialer.
My issues were caused because I was using the Application Context (this.getApplicationContext()). Once I've changed to "this" it worked.
This code works for me :
Where I get the context using :