在Android中的后台运行应用程序

时间:2017-03-25 04:40:14

标签: android android-broadcastreceiver android-intentservice

即使应用已关闭,我也希望在后台运行应用。当有人收到短信时,我需要阅读短信。为此我使用IntentServiceBroadcastReceiver但我不知道为什么代码不起作用。这是我的代码。

清单

 <uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
 <!-- Other code -->
 <service android:name=".ServiceCommunicator"/>

MainActivity

      // Inside onCreate method
     Intent intent = new Intent(this, ServiceCommunicator.class);
     startService(intent);

ServiceCommunicator

 public class ServiceCommunicator extends IntentService
{
private SMSreceiver mSMSreceiver;
private IntentFilter mIntentFilter;

public ServiceCommunicator(){
    super("ServiceCommunicator");
}

@Override
protected void onHandleIntent(Intent intent) {
    mSMSreceiver = new SMSreceiver();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mSMSreceiver, mIntentFilter);
}


private class SMSreceiver extends BroadcastReceiver
{
    private final String TAG = this.getClass().getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle extras = intent.getExtras();

        String strMessage = "";

        if ( extras != null )
        {
            Object[] smsextras = (Object[]) extras.get( "pdus" );

            for ( int i = 0; i < smsextras.length; i++ )
            {
                SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);

                String strMsgBody = smsmsg.getMessageBody().toString();
                String strMsgSrc = smsmsg.getOriginatingAddress();

                strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody;

                Log.i(TAG, strMessage);
                // Show Alert
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context,
                        "senderNum: "+ strMsgSrc + ", message: " + strMsgBody, duration);
                toast.show();
            }

        }

    }

}
 }

此代码有什么问题。即使用户关闭App,我想运行此代码。

1 个答案:

答案 0 :(得分:-2)

我想,你必须使用“服务”。它有助于在后台继续运行应用程序。 这可能有所帮助。

https://www.youtube.com/watch?v=HYctmRwYHOg