[英]how to start service in android without an 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" />
是的,您只需創建一個在應用程序啟動時調用您的服務的BroadCastReceiver即可。 這是我給出的完整答案。 Android - 啟動時啟動服務
如果您不想為您的任何圖標/啟動器應用程序,您也可以這樣做,只是不要創建任何活動
<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">
對於短信發送和接收,你可以查看本教程在android中發送短信
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.