我正在开发一个短信应用程序,它几乎完成并运行良好,但它只在应用程序打开或在后台运行时收到消息,一旦我关闭我的应用程序就停止接收消息。
清单
<receiver
android:name=".SmsBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<service android:name=".ServiceCommunicator"
android:enabled="true"
android:exported="true"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
service.java
public class ServiceCommunicator extends Service {
SmsBroadcastReceiver mSmsBroadcastReceiver;
IntentFilter mIntentFilter;
@Override
public void onCreate() {
super.onCreate();
mSmsBroadcastReceiver=new SmsBroadcastReceiver();
mIntentFilter=new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSmsBroadcastReceiver,mIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mSmsBroadcastReceiver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在MainActivity.java中,我通过调用它来启动服务:
StartService(new Intent(this,ServiceCommunicaor.class));