gpt4 book ai didi

Android BroadcastReceiver 和开始一个 Intent

转载 作者:行者123 更新时间:2023-11-30 04:30:03 25 4
gpt4 key购买 nike

public class SessionManager extends BroadcastReceiver{
Date timeOff;
Date timeOn;

@Override
public void onReceive(Context context, Intent intent) {


if( "android.intent.action.SCREEN_OFF".equals(intent.getAction())) {
Log.i("MobileViaNetReceiver", "Screen off - start time to end session");
timeOff = Calendar.getInstance().getTime();
}

if( "android.intent.action.ACTION_SHUTDOWN".equals(intent.getAction())) {
// DO WHATEVER YOU NEED TO DO HERE
Log.i("MobileViaNetReceiver", "Shut down - log off user");
DbAdapter_User db = new DbAdapter_User(context);
db.open();
db.handleLogout();
db.close();
}

if( "android.intent.action.SCREEN_ON".equals(intent.getAction())) {

timeOn = Calendar.getInstance().getTime();

long diffInMs = timeOn.getTime()-timeOff.getTime();

// convert it to Minutes
long diffInMins = TimeUnit.MILLISECONDS.toMinutes(diffInMs);

if ((int) (diffInMins) > 15) {
//log out user
Log.i("MobileViaNetReceiver", "User inactive for 15 minutes - logout user");
DbAdapter_User db = new DbAdapter_User(context);
db.open(); // ******* HERE *************
db.handleLogout();
db.close();

} else {
Log.i("MobileViaNetReceiver", "User still active");
}
}
}

当屏幕打开时,我正在检查用户是否关闭屏幕超过 15 分钟,如果是,请注销他。并转到 LonIn 屏幕。我想在调用 handleLogout() 时启动一个 Intent (标记为 * HERE **)我可以在类扩展 BroadcastReceiver 时这样做吗?如果没有,我还能做什么?

最佳答案

你需要记住 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

写下错误消息“E/AndroidRuntime( 2339): java.lang.RuntimeException: Unable to start receiver android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context需要 FLAG_ACTIVITY_NEW_TASK 标志。这真的是你想要的吗?”

public class AgeingAutoStartBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

Intent intent1 = new Intent(context,MyMainClass.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
);
}

感谢所有在这里写有用信息的人

关于Android BroadcastReceiver 和开始一个 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7878345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com