我希望我的应用程序使用我的应用程序的自定义振动模式来振动设备。我可以从MainActivity或任何Activity中执行此操作,但我不知道为什么它不能在Java类(SmsReceiver.java)中工作。
我认为,如果我使用...context.getApplicationContext.getSystemService(Context.VIBRATOR_SERVICE);
,它将获得MainActivity上下文,因此有点像我在MainActivity中,它会振动。但不,不。它不会从Receiver类振动。
如何从SmsReceiver.java类中振动手机?
SmsReceiver.java:
package com.app.name.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
Log.d("SNDR", sender);
String message = sb.toString();
// prevent any other broadcast receivers from receiving broadcast
abortBroadcast();
if(!message.isEmpty())
{
if(message == "!")
{
Vibrator v = (Vibrator)context.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
v.cancel();
long[] longs = { 0, 75, 15, 100, 15, 100, 15, 75, 15 };
v.vibrate(longs, -1);
}
}
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
}
MainActivity.java,onButtonClick:
switch(id)
{
case R.id.action_search:
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
long[] longs = { 0, 75, 15, 100, 15, 100, 15, 75, 15 };
v.vibrate(longs, -1);
break;
case R.id.action_settings:
break;
}
This相关问题无法解决此问题。
答案 0 :(得分:3)
我认为使用Vibrator
中的BroadcastReceiver
服务没有任何限制。我认为您的问题与String
比较有关。您应该使用String#equals()
来测试String
平等,而不是==
。
if(message.equals("!"))