当屏幕关闭时按两次电源按钮时,我尝试执行一组代码。下面给出的代码是完美的工作,但我不知道它是否有效或有没有更好的方法来做到这一点。任何变化都表示赞赏。
我已经在前台服务中实现了这个。
MyService.java
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "in onstartcommand()");
IntentFilter inf = new IntentFilter();
inf.addAction(Intent.ACTION_SCREEN_OFF);
inf.addAction(Intent.ACTION_SCREEN_ON);
rec = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
temp_intent = intent;
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if(temp_intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
main_flag+=1;
if(main_flag == 2){
Log.i(TAG, "Double Press Detected ");
//Do Something here
main_flag=1;
}
}
}
}, 1000);
}
}
};
registerReceiver(rec, inf);
return START_STICKY;
}
答案 0 :(得分:0)
您可以通过创建服务来实现这一目标:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
public class UnlockService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
UnlockService getService() {
return UnlockService.this;
}
}
}
然后是接收者:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
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;
Log.e("LOB","wasScreenOn"+wasScreenOn);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e("LOB","userpresent");
Log.e("LOB","wasScreenOn"+wasScreenOn);
String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}
}
添加清单
<service android:name=".UnlockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>