2

when click on volume button change i am using Broadcast receiver to detect the volume change. On that basis I am getting volume this link and when value of volume is zero then I start the MainActivity. But Here my question arise that i do not want to open MianActivity of my app when Music player running means change the volume key at zero then do not want to open my app. But if music player not running in that case i want to open my app MainActivity. How to make this,suggest me thanks.

Here is my Receiver class

public class LaunchReciever extends BroadcastReceiver {

    private Context context=null;
    private static final String TAG="LaunchReciever";
    private static final int SLEEP_TIME = 5000;
    int volumetrap=0;
    @Override
    public void onReceive(Context arg0, Intent intent) {
        context=arg0;
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int volume=(Integer) extras.get("android.media.EXTRA_VOLUME_STREAM_VALUE");
            Toast.makeText(arg0, "Receiver call & volume is:" +volume, Toast.LENGTH_SHORT).show();
            if(volume==0 || volume==7)
            {
                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> appProcesses = activityManager.getRunningTasks(1);
                        String packagename=appProcesses.get(0).topActivity.getPackageName();

                        if(!packagename.equalsIgnoreCase("package name"))
                        {
                        Intent intent=new Intent(context, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);

                        }
                        else{
                            Toast.makeText(context, "Already foreground", Toast.LENGTH_SHORT).show();
                        }

                    }
                }, SLEEP_TIME);
            }

        }
    }
Community
  • 1
  • 1
Sunil Kumar
  • 7,086
  • 4
  • 32
  • 50

0 Answers0