如何以编程方式在android中阻止所有来电和短信

时间:2014-02-27 12:48:53

标签: android

我正在实施拦截器应用程序工作差不多完成但是当我们安装真正的来电应用程序时,会在日志中看到来电。请告诉我如何设置最高优先级。 我的代码在下面给出了我错了,请告诉我。

package com.rsoft.callBlockerService;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import com.rsoft.callBlockerActivities.CallBlockerMainActivity;
import com.rsoft.callListener.ServiceReciever;
import com.rsoft.callblocker.R;
import com.rsoft.messageListener.SmsReceiver;
import com.rsoft.notificationCenter.CallBlockerToastNotification;
import com.rsoft.objects.BlockedContact;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class CallBlockerService extends Service {

    public static final int notification_id = 111;

    // ---------------------------------------
    // Listening Services
    // ---------------------------------------
    private static ServiceReciever service;
    private static SmsReceiver sms;

    // ---------------------------------------
    // Data Structures
    // ---------------------------------------
    public static HashMap<String, BlockedContact> blackList;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        loadData();
        service = new ServiceReciever(getApplicationContext());
        sms = new SmsReceiver();
/*      IntentFilter intentCall = new IntentFilter(
                "android.intent.action.PHONE_STATE");
        intentCall.setPriority(999);
        registerReceiver(service, intentCall);*/
        registerReceiver(service, new IntentFilter(
                "android.intent.action.PHONE_STATE"));
        IntentFilter intentSMS = new IntentFilter(
                "android.provider.Telephony.SMS_RECEIVED");
        intentSMS.setPriority(2147483647);
        registerReceiver(sms, intentSMS);
        // registerReceiver(sms, new
        // IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
        String android_id = Secure.getString(getBaseContext()
                .getContentResolver(), Secure.ANDROID_ID);
        final BlockedContact cn=CallBlockerService.blackList.get(android_id);
        if (cn.getName().equals("0")) {
            showStatusBarNotification("Text Off app is running now");
        } else {

        }
    }

    @Override
    public void onDestroy() {
        //CallBlockerToastNotification
            //  .showDefaultShortNotification("Text Off App Stop");
        service.stopListening();
        unregisterReceiver(service);
        unregisterReceiver(sms);
        service = null;
        sms = null;
        cancelStatusBarNotification();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public void showStatusBarNotification(String message) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent i = new Intent(CallBlockerService.this,
                CallBlockerMainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

        Notification noti = new NotificationCompat.Builder(this)
                .setContentTitle("Text Off notification")
                .setWhen(System.currentTimeMillis()).setContentText(message)
                .setSmallIcon(R.drawable.running_not_icon).setContentIntent(pi)
                .build();

        noti.flags |= Notification.FLAG_NO_CLEAR;

        manager.notify(notification_id, noti);
    }

    public void cancelStatusBarNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(notification_id);
    }

    public void loadData() {
        try {
            FileInputStream fis = openFileInput("CallBlocker.data");
            ObjectInputStream objeto = new ObjectInputStream(fis);
            blackList = (HashMap<String, BlockedContact>) objeto.readObject();
            fis.close();
            objeto.close();
        } catch (Exception e) {
            blackList = new HashMap<String, BlockedContact>();
            Log.e("Error", e.getMessage());
        }
    }

}

1 个答案:

答案 0 :(得分:0)

尝试:

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

编辑:

<强>的AndroidManifest.xml

<receiver android:name=".MySMSReceiver"  android:exported="true">
    <intent-filter android:priority="1">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.BROADCAST_SMS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

MySMSReceiver.class扩展BroadcastReceiver

@Override
public void onReceive(Context context, Intent intent) {
    _context = context;
    if(intent.getAction() != null && intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        SmsMessage smsMessage;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            smsMessage = msgs[0];
        } else {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
        }
        String numberMNS = smsMessage.getDisplayOriginatingAddress();

        if (smsMessage.getDisplayMessageBody().contains("Accept me n:")) {
            String[] parse = smsMessage.getDisplayMessageBody().split("Accept me n:");
            String Nuevonombre = parse[1];
            if (Nuevonombre.length() > 3){
                saveContact(Nuevonombre,numberMNS);
            }else{
                ctx.sendSMS(numberMNS,"Your name must be more than 4 characters.");
            }
        } else {
            boolean check = false;
            for (int i = 0; i < ctx.numbersAdded.length(); i++) {
                try {
                    String num = ctx.numbersAdded.getString(i);
                    if (num.equals(numberMNS)){
                        check = true;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (!check){
                abortBroadcast();
                ctx.sendSMS(numberMNS, "To contact me, send: Accept me n: your full name.");
            }

        }
    }else{
        Toast.makeText(context, "DONT WORK", Toast.LENGTH_LONG).show();
    }
}

<强> Main.class

MySMSReceiver mns = new MySMSReceiver();
mns.ctx = this;
registerReceiver(mns, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

<强>通话

<强> CallHelper.class

interface BackBoolean{
    void returns(boolean check);
}

class CheckPhoneBlock{
    protected void Y(JSONArray conts,String search, BackBoolean call) throws JSONException{
        boolean checkbool = false;
        Log.w("Phones",conts.toString());
        for (int i = 0; i < conts.length();i++){
            String phone = conts.getString(i);
            if (phone.contains(search)){
                checkbool = true;
            }
        }
        call.returns(checkbool);
    }
}

public class CallHelper {

    private MainActivity ctx;
    private TelephonyManager tm;
    private CallStateListener callStateListener;

    private OutgoingReceiver outgoingReceiver;
    private class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, final String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                    try{
                        JSONArray countacts = ctx.contacts.allcontacts;
                        new CheckPhoneBlock().Y(countacts, incomingNumber, new BackBoolean() {
                            @Override
                            public void returns(boolean check) {
                                if (check) {
                                    //Toast.makeText(ctx, "Incoming: " + incomingNumber, Toast.LENGTH_LONG).show();
                                    disconnectCall();
                                    try {
                                        JSONObject newbloqreg = new JSONObject();
                                        newbloqreg.put("name","Bloqueado");
                                        newbloqreg.put("number",incomingNumber);

                                        JSONObject his = ctx.data.getJSONObject("history");
                                        JSONArray llamadas = his.getJSONArray("llamadas");
                                        llamadas.put(newbloqreg);
                                        his.put("llamadas",llamadas);
                                        ctx.data.put("history",his);
                                        ctx.saveDB();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }
                        });

                    }catch (Exception e) {
                        e.printStackTrace();

                    }
                    break;
            }
        }
    }

    public void disconnectCall(){
        try {
            String serviceManagerName = "android.os.ServiceManager";
            String serviceManagerNativeName = "android.os.ServiceManagerNative";
            String telephonyName = "com.android.internal.telephony.ITelephony";
            Class<?> telephonyClass;
            Class<?> telephonyStubClass;
            Class<?> serviceManagerClass;
            Class<?> serviceManagerNativeClass;
            Method telephonyEndCall;
            Object telephonyObject;
            Object serviceManagerObject;
            telephonyClass = Class.forName(telephonyName);
            telephonyStubClass = telephonyClass.getClasses()[0];
            serviceManagerClass = Class.forName(serviceManagerName);
            serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
            Method getService = serviceManagerClass.getMethod("getService", String.class);
            Method tempInterfaceMethod = serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
            Binder tmpBinder = new Binder();
            tmpBinder.attachInterface(null, "fake");
            serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
            IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
            Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
            telephonyObject = serviceMethod.invoke(null, retbinder);
            telephonyEndCall = telephonyClass.getMethod("endCall");
            telephonyEndCall.invoke(telephonyObject);

        } catch (Exception e) {
            e.printStackTrace();
            Log.w("FUCK", "FATAL ERROR: could not connect to telephony subsystem");
            Log.w("FUCK", "Exception object: " + e);
        }
    }

    public class OutgoingReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            Toast.makeText(ctx, "Outgoing: " + number, Toast.LENGTH_LONG).show();
        }
    }


    public CallHelper(MainActivity ctx) {
        this.ctx = ctx;
        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
    }


    public void start() {
        Log.w("START","BROAD");
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        ctx.registerReceiver(outgoingReceiver, intentFilter);
    }

    public void stop() {
        tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
        ctx.unregisterReceiver(outgoingReceiver);
    }

<强> Main.class

CallHelper call = new CallHelper(this);
call.start();