即使应用程序从最近的应用程序托盘中被杀死,单击电源按钮时也会重新启动应用程序

时间:2017-03-06 11:27:48

标签: 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();
    }
}

Service.class

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);
    }
}

BroadcastReciever

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();*/

    }


}

manifest资源配置文件

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>

请告诉我在我的代码中出错的地方,我需要在后台运行该服务,即使在应用程序在后台被杀后也会检查屏幕,因为现在当我杀了应用程序时我无法重启应用程序,但如果我没有杀死它,它工作正常

3 个答案:

答案 0 :(得分:0)

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

中的***

<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);

}

}

答案 1 :(得分:0)

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

在清单

<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;
    }
}

答案 2 :(得分:0)

我知道监听电源按钮的唯一方法是收听 ScreenOn ScreenOff 事件。因此,您可以尝试编写正在侦听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);
    }
}