创建一个自动的启动能够广播接收器在Android中接收器、创建一个、Android

2023-09-13 02:15:22 作者:- 我的微笑,渐渐过期

问题:

我愿意创建一个简单的开始作为一个后台进程,每当一个新的消息进入设备应该将其记录到文件或只显示敬酒消息的应用程序。

I am willing to create an application that simply starts as a background process and whenever a new message comes into the device it should log it into a file or simply display a toast message.

我已经读了很多博客,并试图按照步骤如上。但是,我一直在发甚至在设备日志显示我的设备并没有什么上的消息。我想从Froyo的设备棒棒糖运行它。所以,我不舍得用新的电话服务API支持API 19及更高版本。

I have read a lot of blogs and tried to follow the steps as mentioned. But, I keep on sending messages on my device and nothing displayed not even in device log. I want to run it on devices from Froyo to Lollipop. So, I am not willing to use new Telephony API which supports API 19 and later versions.

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abc.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >



        <receiver android:name=".SMSHandler">

            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

源代码文件

package com.abc.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SMSHandler extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast toast = Toast.makeText(context, "message initiated",
                Toast.LENGTH_LONG);
        toast.show();

        if (intent.getAction()
                .equals("android.provider.Telephony.SMS_RECEIVED")) {
            toast = Toast.makeText(context, "message received",
                    Toast.LENGTH_LONG);
            toast.show();
        }
    }

}

环境:

IDE:

Android的工作室

敏SDK版本:

8

测试的:

在ICS设备(索尼Xperia U) 洁吉(MOTO G)

推荐答案

您需要添加一个活动,然后运行该活动,在此之前的BroadcastReceiver 将工作。

You need to add an activity, then run that activity, before this BroadcastReceiver will work.

更准确地说,一些需要使用明确的意图之前,你的应用程序将被移出停止状态,并允许清单注册 BroadcastReceivers 工作。做到这一点的最简单的方法是有一个发射活动,并运行从启动该活动

More accurately, something needs to use an explicit Intent before your app will be moved out of the stopped state and allow manifest-registered BroadcastReceivers to work. The simplest way to do that is to have a launcher activity, and run that activity from the launcher.

要了解更多信息,请参阅了Android 3.1关于停止应用程序启动控制发行说明,随着这篇博客文章。

To learn more, see "Launch controls on stopped applications" in the Android 3.1 release notes, along with this blog post.