我正在尝试在我的应用程序中实现一项服务,该服务由一个活动启动。该服务如果服务已经启动,它应该在后台运行,直到它被手动停止(由活动)。该服务必须检查每个传入的 SMS 是否有特殊字符串。如果消息包含字符串,则服务应通过发送另一条 SMS(如自动响应系统 (ARS))来响应。第一个问题是服务在 ca 之后被系统停止。60 分钟。此外,如果该服务在系统关闭之前正在运行,则必须在启动后启动该服务。这是该服务的代码:(对于德国人的评论,我很抱歉。我没有时间翻译它们。)
package [...]
import [...]
public class SMSReaderService extends Service {
public static String searchString;
private SMSreceiver mSMSreceiver;
private IntentFilter mIntentFilter;
private static Messenger outMessenger;
private final Messenger inMessenger = new Messenger(new IncomingHandler());
@Override
public void onCreate() {
super.onCreate();
//SMS-received-event receiver
mSMSreceiver = new SMSreceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSMSreceiver, mIntentFilter);
// Loggen, dass das Objekt erstellt wurde
Log.d("SMSReaderService::Created", "SMSReaderService has been Created.");
}
@Override
public IBinder onBind(Intent intent) {
[...]
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
searchString = (String) intent.getExtras().get("SERCHVALUE");
// Loggen, dass der Service gestartet wurde
Log.d("SMSReaderService::Started", "SMSReaderService has Started.");
return ???;
}
@Override
public void onDestroy() {
// Unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
// Loggen, dass das Objekt zerstört wurde
Log.d("SMSReaderService::Object::Destroyed", "SMSReaderService has been destroyed.");
super.onDestroy();
}
private class SMSreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
Bundle extras = intent.getExtras();
if ( extras != null )
{
[...]
}
}
}
}
编辑:
现在服务返回START_STICKY
。我认为这会奏效。(实际上确实如此,但发生错误)。1 小时后,logcat 显示以下信息:
08-03 16:31:29.345: E/AndroidRuntime(9885): java.lang.RuntimeException: Unable to start service de.[...].SMSReaderService@41912c88 with null: java.lang.NullPointerException
08-03 16:31:29.345: E/AndroidRuntime(9885): at de.[...].SMSReaderService.onStartCommand(SMSReaderService.java:161)
08-03 16:32:20.940: E/AndroidRuntime(9933): java.lang.RuntimeException: Unable to start service de.[...].SMSReaderService@41913a30 with null: java.lang.NullPointerException
08-03 16:32:20.940: E/AndroidRuntime(9933): at de.[...].SMSReaderService.onStartCommand(SMSReaderService.java:161)
在“Anwendungsmanager”中(我不知道它是如何用英文调用的......也许像“应用程序管理器”之类的东西)我可以看到服务正在运行...... 1 秒钟。然后它立即停止并尝试重新启动。2次尝试后运行。这是 logcat 记录错误的时候。
第 161 行:
searchString = (String)intent.getExtras().get(GET_SEARCHSTRING_AFTER_START);