Android:在后台运行时发送/接收短信

时间:2014-12-10 22:14:53

标签: java android mobile permissions sms

我的应用程序曾经在后台运行时工作。只要收到短信(基本上是离开的消息),应用程序就会向人发送短信。

通过新的更新,他们删除了BROADCAST_SMS权限,我认为这是允许应用在后台运行的。

所以我的问题是这个,我需要我的应用程序在不显示时工作。换句话说,我的应用程序目前在打开和关注时正常工作,但只要用户将应用程序最小化/发送到后台,该应用程序就不再有效。

以下是manifest.xml背后的代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.katianie.awayreply2"
    android:versionCode="2"
    android:versionName="2.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:persistent="true" >
        <activity
            android:name="com.katianie.awayreply2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

以下是我发送短信的方式:

public void sendTextMessage(String phoneNo, String message)
{
    //Used to detect when the sent text message was/was not delivered.
    String actionStr = "android.provider.Telephony.SMS_DELIVERED";
    Intent theDeliveredIntent = new Intent(actionStr);
    PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(myMainActivity, 0, theDeliveredIntent, 0);
    SmsManager smsManager = SmsManager.getDefault();

    //When the SMS has been delivered, Notify the user with a simple toast.
    myMainActivity.registerReceiver(new BroadcastReceiver() 
    {
        //Called when the away message has gotten to the destination.
        @Override
        public void onReceive(Context arg0, Intent arg1) 
        {
            int resultCode = getResultCode();

            if(resultCode == Activity.RESULT_OK)
            {
                Toast.makeText(myMainActivity.getBaseContext(), "Away message delivered.", Toast.LENGTH_SHORT).show();
            }
            else if(resultCode == Activity.RESULT_CANCELED)
            {
                Toast.makeText(myMainActivity.getBaseContext(), "Away message could NOT be delivered.", Toast.LENGTH_SHORT).show();
            }

            myHasSentMessage = false;

        }
    }, new IntentFilter(actionStr));

    //Send the text message
    if(!myHasSentMessage)
    {
        smsManager.sendTextMessage(phoneNo, null, message, deliveredPendingIntent, null);
    }

}

0 个答案:

没有答案