即使在 sleep 模式(屏幕锁定)后我也试图让振动器保持运行,但应用程序无法运行。我不知道我错过了什么..
除了Wake Lock和BroadcastReceiver还有其他解决方案吗?
(请勿预判,每4点57分震动一次)
public class MainActivity extends Activity {
public BroadcastReceiver vibrateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {0, 3000, 297000};
v.vibrate(pattern, 0);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
@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;
}
}
首先,创建基于报警服务实例的服务调度器。 ……就像那样。
public class ScheduledLocalisationExecutor {
private Context context;
private AlarmManager alarmManager;
private Intent broadcastIntent;
private PendingIntent pendingIntent;
private DbxStart dbxStart;
public ScheduledLocalisationExecutor(Context appContext) {
context = appContext;
dbxStart = new DbxStart();
}
public void setUpScheduledService(long updateTime) {
if (dbxStart.getOpenedDatastore() == null) {
Log.e("DROPBOX", "Dropbox account is not linked...");
return;
}
Log.w("scheduled factory","updating Service!");
broadcastIntent = new Intent(context, LocalisationUpdatesReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + updateTime, pendingIntent);
}
}
现在在 android list 中注册您的广播接收器。
<receiver android:name=".receivers.LocalisationUpdatesReceiver">
</receiver>
并创建您的广播接收器。
public class LocalisationUpdatesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {0, 3000, 297000};
v.vibrate(pattern, 0);
}
}
}
遵循这个方案,你就会成功!
我是一名优秀的程序员,十分优秀!