简体   繁体   中英

Start Activity from service android

I have task to start activity from service and I'm using the following code:

    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); 
    final KeyguardManager.KeyguardLock kl = km .newKeyguardLock("MyKeyguardLock"); 
    kl.disableKeyguard(); 

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
    WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                                     | PowerManager.ACQUIRE_CAUSES_WAKEUP
                                     | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
    wakeLock.acquire();
    Intent i = new Intent(this, someActivity.class);
    i.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    i.putExtra("someName", theName);
    startActivity(i);

This works fine when application is set to background. But when the application is closed the service only unlocks the phone but doesn't start my activity. Any of you have idea how ot achieve needed functionality. Thanks in advance!

EDIT> The problem is somewhere in unlocking phase. On first event occurence the phone get unlocked but doesn't start the activity. On the second occurence if the phone is unlocked the activity starts.

Use this code It will help you.

Intent i = new Intent(context,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
context.startActivity(i); 

//More Clarification Firstly check your app is running or not. If your Application is not running then call this code.

 Intent i = new Intent(context,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
context.startActivity(i); 

If running then use this code

Intent i = new Intent(context,MainActivity.class);    
context.startActivity(i); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM