每当用户双击电源按钮时,我正在创建一个我想要启动活动的程序。
但是,当我启动我的应用程序并点击“主页”按钮并将其最小化时,之后,MyRecevier正在计算LOGCAT中可见的电源按钮计数,但MyReceiver无法启动(在屏幕上显示)最小化活动,即主要活动或任何其他新活动。
记录:
02-28 09:58:06.985: E/In on receive(1166): In Method: ACTION_SCREEN_OFF
02-28 09:58:07.670: E/In on receive(1166): In Method: ACTION_SCREEN_ON
02-28 09:58:38.170: E/In on receive(1166): In Method: ACTION_SCREEN_OFF
02-28 09:59:31.355: E/In on receive(1166): In Method: ACTION_SCREEN_ON
MyReceiver.java:
public class MyReceiver extends BroadcastReceiver
{
private static int countPowerOff = 0;
public MyReceiver ()
{
}
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
Log.e("In on receive", "In Method: ACTION_SCREEN_OFF");
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Log.e("In on receive", "In Method: ACTION_SCREEN_ON");
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
Log.e("In on receive", "In Method: ACTION_USER_PRESENT");
if (countPowerOff > 2)
{
countPowerOff=0;
Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
}
}
}
}
MainActivity.java:
public class MainActivity extends Activity {
private MyReceiver myReceiver;
@Override
protected 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);
filter.addAction(Intent.ACTION_USER_PRESENT);
myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
}
@Override
protected void onDestroy()
{
if (myReceiver != null)
{
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
}
的Manifest.xml: -
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.powermagic.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" />
</application>
答案 0 :(得分:-1)
顺便说一句,if (countPowerOff > 2)
意味着必须按3次。不是两个。点击次数为2时给它一个&gt; =