我知道这与我的问题类似。 https://stackoverflow.com/a/22511290/2208342 但我已经读过,因为Android正在取消该代码,因此该问题的解决方案将变得过时。
qoute取自https://stackoverflow.com/a/5921190/2208342
我不鼓励使用这个解决方案。对于
Android L
,他们正在移除ActivityManager.getRecentTasks()
,并且文档中有相同的注释。所以要警告!
我也听说过这个解决方案不适用于android kitkat。
BroadCastReceiver类
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public IncomingSms(){}
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
Intent intent1 = new Intent(context, CallDetectService.class);
if (context.stopService(intent1)) {
Toast.makeText(context,"if context",Toast.LENGTH_LONG).show();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
String sms = "TEST";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(senderNum, null, sms, null, null);
Toast.makeText(context, "Sms sent Succesfully", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Sms Failed", Toast.LENGTH_LONG).show();
}
Log.i("SmsReciver", "senderNum: " + senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // End For loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReciever", "Exeption smsReceiver" + e);
}
}
else{
Toast.makeText(context,"else context",Toast.LENGTH_LONG).show();
}
}
}
服务类
public class CallDetectService extends Service {
private CallHelper callHelper;
public CallDetectService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
callHelper = new CallHelper(this);
int res = super.onStartCommand(intent, flags, startId);
callHelper.start();
Toast.makeText(getApplicationContext(), "Starting Service", Toast.LENGTH_LONG).show();
return res;
}
@Override
public void onDestroy(){
super.onDestroy();
callHelper.stop();
//Toast.makeText(getApplicationContext(),"Stop Service",Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
}
在我的MainActivity中,我有这段代码,这正是我想要的广播接收器。
Intent intent = new Intent(this,CallDetectService.class);
if (stopService(intent)){
答案 0 :(得分:0)
如果您在活动中使用接收器,则有一种解决方法,但仅 :
将接收者类添加为活动中的内部类
Target _CopyDeployFilesToOutputDirectoryPreserveNewest:
Copying file from 'Data/file1.txt' to 'bin/Release/file1.txt'
public final class MyActivity extends Activity {
public final class IncomingSms extends BroadcastReceiver {
...
}
onStart()/onStop()
中的注意强>
请注意,上述实施方案存在一些缺陷: