我是一名Android初学者。我有两个类,第一个类是:
public class SmsReceiver extends BroadcastReceiver{}
第二类是什么?请提供更多上下文信息。
public class SMS extends Activity{}
我想做的是:当我收到一条短信时,启动一个活动并执行某些操作。但我想使用“服务”而不是“活动”。我的意思是当应用程序启动时,启动服务而不是活动。
这种可能吗?
我是一名Android初学者。我有两个类,第一个类是:
public class SmsReceiver extends BroadcastReceiver{}
public class SMS extends Activity{}
我想做的是:当我收到一条短信时,启动一个活动并执行某些操作。但我想使用“服务”而不是“活动”。我的意思是当应用程序启动时,启动服务而不是活动。
这种可能吗?
从SmsReceiver开始启动您的服务,如下所示:
public class SmsReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
// start service here
Intent intent=new Intent(context,Your_Service.class);
context.startService(intent);
}
else {
}
}
}
并且请确保你已经在 AndroidManifest.xml
中注册了你的服务:
<service android:name="com.xxx.xx.Your_Service" />
您可以通过创建一个广播接收器,在应用程序启动时调用您的服务来实现。这里是我给出的完整答案。Android - Start service on boot
如果您不想为您的应用程序创建任何图标/启动器,也可以这样做,只需不创建任何活动即可。
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
只需像通常声明一样声明您的服务。
当你收到短信时,可以通过广播接收器启动你的服务
@Override
public void onReceive(Context context, Intent intent) {
try {
context.startService(new Intent(context,
YourService.class));
} catch (Exception e) {
Log.d("Unable to start ", "Service on ");
}
请确保在AndroidManifest.xml文件中声明了相应的权限
<uses-permission android:name="android.permission.RECEIVE_SMS">
而且,如果你想要发送和接收短信的话,可以参考一下这个教程在安卓中发送短信