如何按电源按钮启动应用程序

Qad*_*ain 4 android broadcastreceiver android-manifest

我想在用户按下电源按钮时启动我的应用程序.我遵循此代码, 但它没有显示任何Log和吐司.

这是我的完整代码.

MyReceiver.java

import android.content.BroadcastReceiver;
   import android.content.Context;
   import android.content.Intent;
   import android.util.Log;
   import android.widget.Toast;

   public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    // TODO Auto-generated method stub

    Log.v("onReceive", "Power button is pressed.");

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

    // perform what you want here

}

}
Run Code Online (Sandbox Code Playgroud)

menifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.powerbuttontest.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>
    <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>
    </receiver>
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

package com.example.powerbuttontest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
Run Code Online (Sandbox Code Playgroud)
  • 我想我犯了一个错误menifest file.请看看这个.谢谢.

DjH*_*orn 5

首先,与其他广泛的意图不同,对于Intent.ACTION_SCREEN_OFF和Intent.ACTION_SCREEN_ON,您不能在Android Manifest中声明它们!所以你需要制作一个像这样继续运行的服务

public static class UpdateService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            // register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new Receiver();
            registerReceiver(mReceiver, filter);
        }

        @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                // your code
            } else {
                // your code
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

你的接收器可以是某种东西

public class Receiver extends BroadcastReceiver {

    private boolean screenOff;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
        }
        Intent i = new Intent(context, UpdateService.class);
        i.putExtra("screen_state", screenOff);
        context.startService(i);
    }

}
Run Code Online (Sandbox Code Playgroud)


Qad*_*ain 5

这是我完整的代码。希望这可以帮助。我基本上是在做一个外观屏幕应用程序。这将禁用您的默认锁定屏幕。按下电源按钮将启动服务并运行以查找电源按钮按下事件。

Layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/toggleButton1"
    android:layout_marginTop="72dp"
    android:enabled="false"
    android:text="Settings" />

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="72dp"
    android:checked="true"
    android:textOff="Disable"
    android:textOn="Enable" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

package com.example.powerbuttontest;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

ToggleButton btnToggleLock;
Button btnMisc;

Toast toast;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnMisc = (Button) findViewById(R.id.button1);
    btnToggleLock = (ToggleButton) findViewById(R.id.toggleButton1);

    toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);

    btnToggleLock.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (btnToggleLock.isChecked()) {

                toast.cancel();
                toast.setText("Unlocked");
                toast.show();

                Log.i("Unlocked", "If");

                Context context = getApplicationContext();
                KeyguardManager _guard = (KeyguardManager) context
                        .getSystemService(Context.KEYGUARD_SERVICE);
                KeyguardLock _keyguardLock = _guard
                        .newKeyguardLock("KeyguardLockWrapper");
                _keyguardLock.disableKeyguard();

                MainActivity.this.startService(new Intent(
                        MainActivity.this, UpdateService.class));

            } else {

                toast.cancel();
                toast.setText("Locked");
                toast.show();

                Context context = getApplicationContext();
                KeyguardManager _guard = (KeyguardManager) context
                        .getSystemService(Context.KEYGUARD_SERVICE);
                KeyguardLock _keyguardLock = _guard
                        .newKeyguardLock("KeyguardLockWrapper");
                _keyguardLock.reenableKeyguard();

                Log.i("Locked", "else");

                MainActivity.this.stopService(new Intent(MainActivity.this,
                        UpdateService.class));

            }

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    super.onConfigurationChanged(newConfig);

    Log.i("onConfigurationChanged", "Called");
}

}
Run Code Online (Sandbox Code Playgroud)

MyReciever.java

package com.example.powerbuttontest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    Intent i = new Intent(context, UpdateService.class);
    i.putExtra("screen_state", screenOff);
    context.startService(i);
}

}
Run Code Online (Sandbox Code Playgroud)

UpdateService.java

package com.example.powerbuttontest;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class UpdateService extends Service {

    BroadcastReceiver mReceiver;

@Override
public void onCreate() {
    super.onCreate();
    // register receiver that handles screen on and screen off logic
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    mReceiver = new MyReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public void onDestroy() {

    unregisterReceiver(mReceiver);
    Log.i("onDestroy Reciever", "Called");

    super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
    boolean screenOn = intent.getBooleanExtra("screen_state", false);
    if (!screenOn) {
        Log.i("screenON", "Called");
        Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
                .show();
    } else {
        Log.i("screenOFF", "Called");
        // Toast.makeText(getApplicationContext(), "Sleep",
        // Toast.LENGTH_LONG)
        // .show();
    }
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
}
Run Code Online (Sandbox Code Playgroud)

Menifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <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>

    <receiver android:name=".MyReceiver" />

    <service android:name=".UpdateService" />
</application>

</manifest>
Run Code Online (Sandbox Code Playgroud)