我试图在睡眠模式(屏幕锁定)之后保持振动器运行,但应用程序将无法工作。我不知道我错过了什么..
除了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;
}
}
答案 0 :(得分:1)
首先根据例如警报服务创建服务调度程序。 STH。那样的。
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清单中注册您的广播接收器。
<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);
}
}
}
遵循该计划,您将获得成功!
答案 1 :(得分:0)
BroadcastReceiver.onReceive()
不适用于长时间操作。您应该在其他地方(vibrate()
或更好的Service
)致电IntentService
。
此外,振动模式运行时间太长。如果我是你,我会安排vibrate()
通过Android的调度机制每隔4:57运行一个简短模式,称为AlarmManager
。这个想法是,写一个调用BroadcastReceiver.onReceive()
的{{1}}并安排每次运行BroadcastReceiver(或更好,因为你需要一个部分唤醒锁来绕过睡眠模式写一个startService(yourservice)
调用WakefulBroadcastReceiver.onReceive()
)。不要忘记在服务结束时拨打startWakefulService()
以释放唤醒锁。
如果您仍然希望您的服务执行长时间运行的振动模式,那么这个想法是一样的。
答案 2 :(得分:0)