我是 android 新手,我已经创建了这样的 Intent -
<receiver android:name=".IncommigCallListener" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".OutgoingCallReciever" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
现在我创建了这样的服务-
<service
android:name=".CallLogger"
android:exported="false"/>
类(class)
CallLogger
public class CallLogger extends IntentService {
public CallLogger(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("service started");
}
}
我不想在我的应用程序中进行任何 Activity ,我只想启动服务以便它可以在后台工作并接收
PHONE_STATE
和 NEW_OUTGOING_CALL
Intent 。当我启动此应用程序时,它不会在
PHONE_STATE
上记录任何内容或 NEW_OUTGOING_CALL
Intent 。如何在不使用任何 Activity 的情况下在后台启动服务?
编辑:
public class OutgoingCallReciever extends BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
}
和
public class IncommigCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String incommingCallNumber = incomingNumber;
System.out.println("incomming call : " + incomingNumber);
break;
}
}
}
最佳答案
只需在 BroadcastReceiver 的 onReceive 方法中启动服务即可。当您在 AndroidManifist 中注册 BroadcastReceiver 时,即使应用程序未运行(操作系统将为您运行它),它也会始终监听广播。
示例
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
编辑
要在启动完成时启动服务,您可以执行以下操作。
1) 为您的 Manifist 添加权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) 使用 BOOT COMPLETE 操作注册您的广播接收器。
<receiver android:name="com.example.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3) 在 BootBroadcastReceiver.java 中:
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent );
}
}
关于android - 在后台听 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16814924/