Starting an Activity from BroadcastReceiver in Ser

2019-03-04 19:06发布

问题:

I am trying to start an activity at a certain time with the help of a service and broadcastreceiver. The problem is, once the time hits, my app crashes.

Here's my AlarmService class that extends Service Assume that everything works besides the intent stated in the code.

public void onCreate(){

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    Intent i = new Intent(this, GoTime.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context c, Intent i) {    

          if(checkquery((currentTime < (startTime)))){

            // RINGER is set to Vibrate.
            audioManager.setRingerMode(1);  

            startActivity(i); //This crashes the app. If i take out this, everything works.
          }
        }
    };

    registerReceiver(myReceiver, new IntentFilter("setVibrate") );                    
    alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));     
}

The reason i believe its not working is because i already have an intent filter to make the phone vibrate. Not sure what else to do or how to change it.

What i am trying to do is, to create an alarm clock, and once a time hits, i want it to start ringing, then start an activity that would display the snooze.

The reason its on vibrate right now is just so it doesn't ring everytime i am trying to test it.

Any tips and advice would be appreciated. Thank you.

Edit:

I've tried using the flag activity new task, and this is my logcat:

08-01 15:23:00.508: E/AndroidRuntime(2244): FATAL EXCEPTION: main
08-01 15:23:00.508: E/AndroidRuntime(2244): java.lang.RuntimeException: Error receiving broadcast Intent { act=setVibrate flg=0x14 (has extras) } in cs.AlarmManagerService$1@42093aa0
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.os.Handler.handleCallback(Handler.java:725)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.os.Looper.loop(Looper.java:137)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.app.ActivityThread.main(ActivityThread.java:5293)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at java.lang.reflect.Method.invokeNative(Native Method)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at java.lang.reflect.Method.invoke(Method.java:511)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at dalvik.system.NativeStart.main(Native Method)
08-01 15:23:00.508: E/AndroidRuntime(2244): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.app.ContextImpl.startActivity(ContextImpl.java:1235)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.app.ContextImpl.startActivity(ContextImpl.java:1222)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.content.ContextWrapper.startActivity(ContextWrapper.java:291)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at cs.AlarmManagerService$1.onReceive(AlarmManagerService.java:70)
08-01 15:23:00.508: E/AndroidRuntime(2244):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:758)
08-01 15:23:00.508: E/AndroidRuntime(2244):     ... 9 more

Edit2:

Ok so after some more researching, i tried:

Intent mIntent = new Intent(getBaseContext(), GoTime.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(mIntent);

and this time, it worked. Thank you for all of your time!

回答1:

To start an Activity outside of an Activity Context you need to use the flag FLAG_ACTIVITY_NEW_TASK. Add this to your Intent

 Intent in = new Intent(this, GoTime.class);
 in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

if this doesn't solve your problem then please post the logcat.

Intent



回答2:

I would like to point out that starting activities from the background is not a great experience for the user. Suppose the user is in the midst of some other work? Arbitrarily starting a new Activity is at the very least an annoyance.

I think that what you should do is send a notification from your Service, with a content Intent leads to the activity you want to start. This gives users the choice to go to the activity as soon as the notification appears or wait until they're finished with their current work before going to the activity.

Perhaps I've misunderstood what you want to do, but you may want to consider amending your app design.

The Notifications API guide discusses this in more detail. There's also an Android training class called Notifying the User