Reputation: 2063
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");
}
}
}
When the screen is turned ON I am checking if the user has turned scrren off for more than 15 mins, if yes, logout him. And go to LonIn screen. I want to start an intent when I call that handleLogout() (marked * HERE **) Can I do that when class extends BroadcastReceiver ? If no, what else can I do ?
Upvotes: 1
Views: 643
Reputation: 5532
You need to remember intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Blessings and happiness to the Google engineer who wrote the followint error message "E/AndroidRuntime( 2339): java.lang.RuntimeException: Unable to start receiver android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?"
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);
);
}
}
Thanks to everyone who writes helpful messages here
Upvotes: 1
Reputation: 30825
Yes, you can do that. You just use the context that was passed into your onRecieve function when you're creating your Intent. Once you have the Intent, make this call:
Context.startActivity(yourIntent);
Upvotes: 0
Reputation: 9908
You certainly can. Try
Intent yourIntent = new Intent(context, YourActivity.class);
startActivity(yourIntent);
If you want to do it in your handleLogout
method, pass in the Context.
private method handleLogout(Context context) {
...
}
Upvotes: 0