【问题标题】:Restarting the app when power button is clicked even after the app is killed from recent application tray即使在最近的应用程序托盘中杀死了应用程序后,单击电源按钮时仍会重新启动应用程序
【发布时间】:2017-07-26 06:03:31
【问题描述】:

我是新的 android,我想在我的系统中实现,当我按下电源按钮时,我需要打开应用程序,但应用程序在最近的应用程序托盘的后台被杀死。我正在尝试所有我得到的解决方案,但我没有得到解决方案

MainActivity.class

public class MainActivity extends ActionBarActivity {

  Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        setContentView(R.layout.activity_main);
        /*Toast.makeText(getApplicationContext(),"main Activity run",Toast.LENGTH_SHORT).show();
        intent = new Intent(new Intent(getBaseContext(), PowerService.class));
        startService(intent);*/
//     /*   new Handler().post(new Runnable() {
//            @Override
//            public void run() {
                Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
                startService(intent);
//            }
//        });
//*/

//        Intent notificationIntent = new Intent(this, PowerService.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//
//    
//


    }


    @Override
    protected void onStart() {




        Toast.makeText(getApplicationContext(),"inside mainactivity onStart",Toast.LENGTH_SHORT).show();
        super.onStart();
    }

    @Override
    protected void onResume() {
        Toast.makeText(getApplicationContext(),"inside mainactivity onResume",Toast.LENGTH_SHORT).show();
        super.onResume();
    }

    @Override
    protected void onRestart() {
        Toast.makeText(getApplicationContext(),"inside mainactivity onRestart",Toast.LENGTH_SHORT).show();
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        Toast.makeText(getApplicationContext(),"inside mainactivity onDestroy",Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
        startService(intent);
        Toast.makeText(getApplicationContext(),"inside mainactivity onStop",Toast.LENGTH_SHORT).show();
        super.onStop();
    }
}

服务类

public class PowerService extends Service {

    BroadcastReceiver mReceiver;
    IntentFilter filter;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        cpuWakeLock.acquire();
        registerReciver();

        return Service.START_STICKY;
    }
    public class LocalBinder extends Binder {
        PowerService getService() {
            return PowerService.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("inside powerservice onUnbind");
        Toast.makeText(getApplicationContext(),"inside powerservice onUnbind",Toast.LENGTH_SHORT).show();
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        System.out.println("inside powerservice onRebind");
        Toast.makeText(getApplicationContext(),"inside powerservice onRebind",Toast.LENGTH_SHORT).show();
        super.onRebind(intent);
    }

    @Override
    public void onStart(Intent intent, int startId) {

        System.out.println("inside powerservice onStart");

        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        //unregisterReceiver(mReceiver);
        //registerReciver();
        System.out.println("inside powerservice onDestroy");
        Toast.makeText(getApplicationContext(),"inside powerservice ondestroy",Toast.LENGTH_SHORT).show();
        startService(new Intent(this, PowerService.class));
        super.onDestroy();



    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        /*registerReciver();
        startService(new Intent(this,PowerService.class));*/
        Toast.makeText(getApplicationContext(),"inside powerservice onTaskRemoved",Toast.LENGTH_SHORT).show();
        /*Intent broadcastIntent = new Intent(this,AppReciever.class);
        sendBroadcast(broadcastIntent);
        super.onTaskRemoved(rootIntent);*/
      /*  Intent restartServiceTask = new Intent(this,PowerService.class);
        restartServiceTask.setPackage(getPackageName());
        PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        myAlarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartPendingIntent);


        startService(new Intent(this,PowerService.class));*/
        super.onTaskRemoved(rootIntent);
    }

    public void registerReciver()
    {
        filter= new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_LOCKED_BOOT_COMPLETED);
         mReceiver = new AppReciever();
        registerReceiver(mReceiver, filter);
    }
}

广播接收器

public class AppReciever extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    public void onReceive(final Context context, final Intent intent) {
        Log.e("LOB", "onReceive");

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = false;
            Toast.makeText(context,"inside ACTION_SCREEN_OFF",Toast.LENGTH_SHORT).show();
            //Log.e("LOB","wasScreenOn"+wasScreenOn);
            Log.e("Screen ", "shutdown now");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here

            Log.e("Screen ", "awaked now");
            Toast.makeText(context,"inside ACTION_SCREEN_ON",Toast.LENGTH_SHORT).show();

            Intent i = new Intent(context, MainActivity.class);  //MyActivity can be anything which you want to start on bootup...
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);

        } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            Log.e("LOB", "userpresent");
            Toast.makeText(context,"inside ACTION_USER_PRESENT",Toast.LENGTH_SHORT).show();
            Intent ii = new Intent(context, MainActivity.class);  //MyActivity can be anything which you want to start on bootup...
            ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ii);
            wasScreenOn = true;
            //  Log.e("LOB","wasScreenOn"+wasScreenOn);


        }
        else if(intent.getAction().equals(Intent.ACTION_LOCKED_BOOT_COMPLETED))
        {
            Toast.makeText(context,"inside ACTION_LOCKED_BOOT_COMPLETED",Toast.LENGTH_SHORT).show();
            Log.e("LOB", "userpresent");
            Intent ii = new Intent(context, MainActivity.class);  //MyActivity can be anything which you want to start on bootup...
            ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ii);
        }




       /* Log.v("#@%@%#", "Power button is pressed.");

        Toast.makeText(context, "power button clicked",Toast.LENGTH_LONG).show();*/

    }


}

清单文件

package="com.benayah.app.sampleapp">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".PowerService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:process=":my_process"
            >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.SCREEN_OFF"></action>
                <action android:name="android.intent.action.SCREEN_ON"></action>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
                <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
            </intent-filter>
        </service>
    </application>

请让我知道我的代码哪里出错了,我需要在后台运行服务以检查屏幕,即使应用程序在后台被杀死,因为现在当我杀死应用程序时,我无法重新启动我的应用程序,但如果我没有杀死它,它工作正常

【问题讨论】:

    标签: android


    【解决方案1】:

    使用以下可能会有所帮助...

    ***在清单中

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
     <receiver android:name=".BootCompleteReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    

    public class BootCompleteReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        Intent intent= new Intent(context, ActivitySample.class);
        context.startActivity(intent);
    
    }
    

    }

    【讨论】:

      【解决方案2】:

      下面的你可能会有所帮助...

      在清单中

      <receiver android:name=".MyReceiver">
      <intent-filter>
          <action android:name="android.intent.action.SCREEN_OFF"></action>
          <action android:name="android.intent.action.SCREEN_ON"></action>
          <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
          <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
           <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
      </intent-filter>
      

      public class MyReceiver extends BroadcastReceiver {
      static int countPowerOff=0;
      private Activity activity=null;
      public MyReceiver (Activity activity)
      {
      this.activity=activity;
      }
      @Override
      public void onReceive(Context context, Intent intent) {
      
        Log.v("onReceive", "Power button is pressed.");
      
        Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
               .show();
      
       if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) 
       {
      countPowerOff++;    
       } 
       else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) 
       {
        if(countPowerOff==5)
        {
            Intent i =new Intent(activity,NewActivity.class);
            activity.startActivity(i);
         }
      }
      
      }
      

      还有,

      公共类 MainActivity 扩展 Activity {

          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
              filter.addAction(Intent.ACTION_SCREEN_OFF);
              MyReceiver mReceiver = new MyReceiver (this);
              registerReceiver(mReceiver, filter);
          }
      
          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.activity_main, menu);
              return true;
          }
      }
      

      【讨论】:

        【解决方案3】:

        我知道监控电源按钮的唯一方法是监听 ScreenOnScreenOff 事件。因此,您可以尝试编写一个正在侦听 ScreenOn 或 ScreenOff 的服务,然后每次触发此事件时,您都可以启动所需的应用程序。

        MainActivity:

        public class MainActivity extends AppCompatActivity {
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
                Intent intent = new Intent(this, ScreenOnOffService.class);
                startService(intent);
            }
        }
        

        服务:

        public class ScreenOnOffService extends Service {
        
            private ScreenOnOffReceiver mScreenReceiver;
        
            @Nullable
            @Override
            public IBinder onBind(Intent intent) {
                return null;
            }
        
            @Override
            public void onCreate() {
                registerScreenStatusReceiver();
            }
        
            @Override
            public void onDestroy() {
                unregisterScreenStatusReceiver();
            }
        
            private void registerScreenStatusReceiver() {
                mScreenReceiver = new ScreenOnOffReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction(Intent.ACTION_SCREEN_OFF);
                filter.addAction(Intent.ACTION_SCREEN_ON);
                registerReceiver(mScreenReceiver, filter);
            }
        
            private void unregisterScreenStatusReceiver() {
                try {
                    if (mScreenReceiver != null) {
                        unregisterReceiver(mScreenReceiver);
                    }
                } catch (IllegalArgumentException e) {}
            }
        }
        

        清单:

        <service android:name="com.benayah.app.sampleapp.ScreenOnOffService" />
        

        广播接收者:

        (这里需要输入你要启动的应用的包名) 在我的示例中,我输入了您的包名称:com.benayah.app.sampleapp

        public class ScreenOnOffReceiver extends BroadcastReceiver {
        
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    Log.d("StackOverflow", "Screen Off");
                    startApp(context);
        
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    Log.d("StackOverflow", "Screen On");
                    startApp(context);
                }
            }
        
            private void startApp(Context context) {
                PackageManager pm = context.getPackageManager();
                Intent launchIntent = pm.getLaunchIntentForPackage("com.benayah.app.sampleapp");
                context.startActivity(launchIntent);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多