Search code examples
androidandroid-activityservicelauncherbroadcasting

Launching different activities


I have two activities.one is main activity and second is lock screen activity.what main activity contains the content of the application and the lock screen activity displays the lock screen. what i want is that when the user opens the app it should display main activity. but when the user plugs in the charger it should automatically open the lock screen activity even if the application is closed. I have done all of the work required to do this.but when the user plugs in the charger it runs main activity instead of lock screen activity. if anyone knows how to open lock screen activity on plug in charger and normally it should display main activity then please tell me how? any help is appreciated


Solution

  • You need to use Broadcast Receiver when user plugin charger then your app receive broadcast.

    in Menifest

    <receiver android:name=".PlugInReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>
    

    your reciever class

    public class PlugInReceiver extends BroadcastReceiver {
    public void onReceive(Context context , Intent intent) {
    
    String action = intent.getAction();
    
           if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
               // Do something when power connected
           }
           else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
               // Do something when power disconnected
           }
       }
    }