常用的一些api

发送手机短信

// 发送短信给安全号码
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone, null,"sim card changed!", null, null);

设置接受广播的优先级最高也就是inter里面的最大值。你可以看api,然后转化为十进制。应该是这个 2147483647。

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

播放一些小聲音

// 播放报警音乐, 即使手机调为静音,也能播放音乐, 因为使用的是媒体声音的通道,和铃声无关
                MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
                player.setVolume(1f, 1f);
                player.setLooping(true);
                player.start();

短信的广播接受者

package com.itheima52.mobilesafe.receiver;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.service.LocationService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.sax.StartElementListener;
import android.telephony.SmsMessage;

/** * 拦截短信 * * @author Kevin * */
public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Object[] objects = (Object[]) intent.getExtras().get("pdus");

        for (Object object : objects) {// 短信最多140字节,
                                        // 超出的话,会分为多条短信发送,所以是一个数组,因为我们的短信指令很短,所以for循环只执行一次
            SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
            String originatingAddress = message.getOriginatingAddress();// 短信来源号码
            String messageBody = message.getMessageBody();// 短信内容

            System.out.println(originatingAddress + ":" + messageBody);

            if ("#*alarm*#".equals(messageBody)) {
                // 播放报警音乐, 即使手机调为静音,也能播放音乐, 因为使用的是媒体声音的通道,和铃声无关
                MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
                player.setVolume(1f, 1f);
                player.setLooping(true);
                player.start();

                abortBroadcast();// 中断短信的传递, 从而系统短信app就收不到内容了
            } else if ("#*location*#".equals(messageBody)) {
                // 获取经纬度坐标
                context.startService(new Intent(context, LocationService.class));// 开启定位服务

                SharedPreferences sp = context.getSharedPreferences("config",
                        Context.MODE_PRIVATE);
                String location = sp.getString("location",
                        "getting location...");

                System.out.println("location:" + location);

                abortBroadcast();// 中断短信的传递, 从而系统短信app就收不到内容了
            } else if ("#*wipedata*#".equals(messageBody)) {
                System.out.println("远程清除数据");
                abortBroadcast();
            } else if ("#*lockscreen*#".equals(messageBody)) {
                System.out.println("远程锁屏");
                abortBroadcast();
            }
        }
    }

}

手机定位

package com.itheima52.location;

import java.util.List;

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView tvLocation;
    private LocationManager lm;
    private MyLocationListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvLocation = (TextView) findViewById(R.id.tv_location);

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        List<String> allProviders = lm.getAllProviders();// 获取所有位置提供者
        System.out.println(allProviders);

        listener = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);// 参1表示位置提供者,参2表示最短更新时间,参3表示最短更新距离
    }

    class MyLocationListener implements LocationListener {

        // 位置发生变化
        @Override
        public void onLocationChanged(Location location) {
            String j = "经度:" + location.getLongitude();
            String w = "纬度:" + location.getLatitude();
            String accuracy = "精确度:" + location.getAccuracy();
            String altitude = "海拔:" + location.getAltitude();

            tvLocation
                    .setText(j + "\n" + w + "\n" + accuracy + "\n" + altitude);
        }

        // 位置提供者状态发生变化
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            System.out.println("onStatusChanged");
        }

        // 用户打开gps
        @Override
        public void onProviderEnabled(String provider) {
            System.out.println("onProviderEnabled");
        }

        // 用户关闭gps
        @Override
        public void onProviderDisabled(String provider) {
            System.out.println("onProviderDisabled");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(listener);// 当activity销毁时,停止更新位置, 节省电量
    }

}

选择最优定位定位

package com.itheima52.mobilesafe.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

/** * 获取经纬度坐标的service * * @author Kevin * */
public class LocationService extends Service {

    private LocationManager lm;
    private MyLocationListener listener;
    private SharedPreferences mPref;

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

    @Override
    public void onCreate() {
        super.onCreate();

        mPref = getSharedPreferences("config", MODE_PRIVATE);

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        // List<String> allProviders = lm.getAllProviders();// 获取所有位置提供者
        // System.out.println(allProviders);

        Criteria criteria = new Criteria();
        criteria.setCostAllowed(true);// 是否允许付费,比如使用3g网络定位
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String bestProvider = lm.getBestProvider(criteria, true);// 获取最佳位置提供者

        listener = new MyLocationListener();
        lm.requestLocationUpdates(bestProvider, 0, 0, listener);// 参1表示位置提供者,参2表示最短更新时间,参3表示最短更新距离
    }

    class MyLocationListener implements LocationListener {

        // 位置发生变化
        @Override
        public void onLocationChanged(Location location) {
            System.out.println("get location!");

            // 将获取的经纬度保存在sp中
            mPref.edit()
                    .putString(
                            "location",
                            "j:" + location.getLongitude() + "; w:"
                                    + location.getLatitude()).commit();

            stopSelf();//停掉service
        }

        // 位置提供者状态发生变化
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            System.out.println("onStatusChanged");
        }

        // 用户打开gps
        @Override
        public void onProviderEnabled(String provider) {
            System.out.println("onProviderEnabled");
        }

        // 用户关闭gps
        @Override
        public void onProviderDisabled(String provider) {
            System.out.println("onProviderDisabled");
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(listener);// 当activity销毁时,停止更新位置, 节省电量
    }

}

监听输入框文字变化

// 监听EditText的变化
        etNumber.addTextChangedListener(new TextWatcher() {

            // 文字 发生变化时的回调
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                String address = AddressDao.getAddress(s.toString());
                tvResult.setText(address);
            }

            // 文字变化前的回调
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            // 文字变化结束之后的回调
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

访问已经有的数据库

package com.itheima52.mobilesafe.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/** * 归属地查询工具 * * @author Kevin * */
public class AddressDao {

    private static final String PATH = "data/data/com.itheima52.mobilesafe/files/address.db";// 注意,该路径必须是data/data目录的文件,否则数据库访问不到

    public static String getAddress(String number) {
        String address = "未知号码";

        // 获取数据库对象
        SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH, null,
                SQLiteDatabase.OPEN_READONLY);

        // 手机号码特点: 1 + (3,4,5,6,7,8) + (9位数字)
        // 正则表达式
        // ^1[3-8]\d{9}$

        if (number.matches("^1[3-8]\\d{9}$")) {// 匹配手机号码
            Cursor cursor = database
                    .rawQuery(
                            "select location from data2 where id=(select outkey from data1 where id=?)",
                            new String[] { number.substring(0, 7) });

            if (cursor.moveToNext()) {
                address = cursor.getString(0);
            }

            cursor.close();
        } else if (number.matches("^\\d+$")) {// 匹配数字
            switch (number.length()) {
            case 3:
                address = "报警电话";
                break;
            case 4:
                address = "模拟器";
                break;
            case 5:
                address = "客服电话";
                break;
            case 7:
            case 8:
                address = "本地电话";
                break;
            default:
                // 01088881234
                // 048388888888
                if (number.startsWith("0") && number.length() > 10) {// 有可能是长途电话
                    // 有些区号是4位,有些区号是3位(包括0)

                    // 先查询4位区号
                    Cursor cursor = database.rawQuery(
                            "select location from data2 where area =?",
                            new String[] { number.substring(1, 4) });

                    if (cursor.moveToNext()) {
                        address = cursor.getString(0);
                    } else {
                        cursor.close();

                        // 查询3位区号
                        cursor = database.rawQuery(
                                "select location from data2 where area =?",
                                new String[] { number.substring(1, 3) });

                        if (cursor.moveToNext()) {
                            address = cursor.getString(0);
                        }

                        cursor.close();
                    }
                }
                break;
            }
        }

        database.close();// 关闭数据库
        return address;
    }
}

振动器

/** * 手机震动, 需要权限 android.permission.VIBRATE */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        // vibrator.vibrate(2000);震动两秒
        vibrator.vibrate(new long[] { 1000, 2000, 1000, 3000 }, -1);// 先等待1秒,再震动2秒,再等待1秒,再震动3秒,
                                                                    // 参2等于-1表示只执行一次,不循环,
                                                                    // 参2等于0表示从头循环,
                                                                    // 参2表示从第几个位置开始循环
        // 取消震动vibrator.cancel()
    }

接受来电做一些事情

package com.itheima52.mobilesafe.service;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.db.dao.AddressDao;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

/** * 来电提醒的服务 * * @author Kevin * */
public class AddressService extends Service {

    private TelephonyManager tm;
    private MyListener listener;
    private OutCallReceiver receiver;
    private WindowManager mWM;
    private View view;
    private SharedPreferences mPref;

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

    @Override
    public void onCreate() {
        super.onCreate();

        mPref = getSharedPreferences("config", MODE_PRIVATE);

        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        listener = new MyListener();
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);// 监听来电的状态

        receiver = new OutCallReceiver();

        IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        registerReceiver(receiver, filter);// 动态注册广播
    }

    class MyListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:// 电话铃声响了
                System.out.println("电话铃响...");
                String address = AddressDao.getAddress(incomingNumber);// 根据来电号码查询归属地
                // Toast.makeText(AddressService.this, address,
                // Toast.LENGTH_LONG)
                // .show();
                showToast(address);
                break;

            case TelephonyManager.CALL_STATE_IDLE:// 电话闲置状态
                if (mWM != null && view != null) {
                    mWM.removeView(view);// 从window中移除view
                    view = null;
                }
                break;
            default:
                break;
            }

            super.onCallStateChanged(state, incomingNumber);
        }

    }

    /** * 监听去电的广播接受者 需要权限: android.permission.PROCESS_OUTGOING_CALLS * * @author Kevin * */
    class OutCallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String number = getResultData();// 获取去电电话号码

            String address = AddressDao.getAddress(number);
            // Toast.makeText(context, address, Toast.LENGTH_LONG).show();
            showToast(address);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tm.listen(listener, PhoneStateListener.LISTEN_NONE);// 停止来电监听

        unregisterReceiver(receiver);// 注销广播
    }

    /** * 自定义归属地浮窗 */
    private void showToast(String text) {
        mWM = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.setTitle("Toast");

        // view = new TextView(this);
        view = View.inflate(this, R.layout.toast_address, null);

        int[] bgs = new int[] { R.drawable.call_locate_white,
                R.drawable.call_locate_orange, R.drawable.call_locate_blue,
                R.drawable.call_locate_gray, R.drawable.call_locate_green };
        int style = mPref.getInt("address_style", 0);

        view.setBackgroundResource(bgs[style]);// 根据存储的样式更新背景

        TextView tvText = (TextView) view.findViewById(R.id.tv_number);
        tvText.setText(text);

        mWM.addView(view, params);// 将view添加在屏幕上(Window)
    }

}
//获取到rom内存的运行的剩余空间
        long rom_freeSpace = Environment.getDataDirectory().getFreeSpace();
        //获取到SD卡的剩余空间
        long sd_freeSpace = Environment.getExternalStorageDirectory().getFreeSpace();

        System.out.println("内存可用:" + rom_freeSpace);

        System.out.println("sd卡可用:" + sd_freeSpace);

        //格式化大小
        tv_rom.setText("内存可用:" + Formatter.formatFileSize(this, rom_freeSpace));
        tv_sd.setText("sd卡可用" + Formatter.formatFileSize(this, sd_freeSpace));

文本复制到剪切板

@SuppressWarnings("deprecation")
    public static void copyTextToBoard(String string) {
        if (TextUtils.isEmpty(string))
            return;
        ClipboardManager clip = (ClipboardManager) BaseApplication.context()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setText(string);
        AppContext.showToast(R.string.copy_success);
    }

你可能感兴趣的:(api,手机)