AndroidのAndroidモバイル開発 - コールシステムサービス(振動、アラーム、電話ネットワークオペレータを表示)完全なコード

次のように完全なコードがある(コメントの重要な一部となっているため)

  • マニフェストファイル:
//访问手机识别码权限(以便看手机网络运行商名称),一个权限即使是动态申请,也要先声明
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
//手机振动权限
<uses-permission android:name="android.permission.VIBRATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    //注册闹铃服务
    <service android:name=".MessageService"></service>
</application>
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/vibrator_start_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="振动服务启动" />

        <Button
            android:id="@+id/vibrator_stop_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="振动服务停止" />

        <Button
            android:id="@+id/alarm_start_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="闹铃服务启动" />

        <Button
            android:id="@+id/alarm_stop_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="闹铃服务停止" />

        <Button
            android:id="@+id/SIM_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="查看手机网络运行商名称" />
 </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_main.xmlはページショーの結果:
ここに画像を挿入説明

  • MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //按钮的全局变量,以及TAG
    private Button vibrator_btn;
    private Button alarm_start_btn;
    private Button alarm_stop_btn;
    private Button SIM_btn;
    private String TAG = "MainActivity";

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

        //各种按钮定义
        vibrator_btn = findViewById(R.id.vibrator_start_btn); //振动器开始振动
        vibrator_btn.setOnClickListener(this);
        vibrator_btn = findViewById(R.id.vibrator_stop_btn); //振动器停止震动
        vibrator_btn.setOnClickListener(this);
        alarm_start_btn = findViewById(R.id.alarm_start_btn); //闹铃开始服务
        alarm_start_btn.setOnClickListener(this);
        alarm_stop_btn = findViewById(R.id.alarm_stop_btn); //闹铃停止服务
        alarm_stop_btn.setOnClickListener(this);
        SIM_btn = findViewById(R.id.SIM_btn); //读取SIM卡,确定手机网络运营商名称
        SIM_btn.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        
        //系统服务-振动器
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        //下面这两步是为了后面闹铃set和cancle方法写的
        Intent service = new Intent(this, MessageService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, service, 0);
        //系统服务-闹铃
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        switch (v.getId()) {
            
            //振动器震动
            case R.id.vibrator_start_btn:
                if (vibrator.hasVibrator()) {
                    Toast.makeText(getApplicationContext(), "振动器振动五秒", Toast.LENGTH_SHORT).show();
                    vibrator.vibrate(5 * 1000);
                } else {
                    Toast.makeText(getApplicationContext(), "该设备没有振动器哦", Toast.LENGTH_SHORT).show();
                }
                break;
            //震动器停止
            case R.id.vibrator_stop_btn:
                vibrator.cancel();
                Toast.makeText(getApplicationContext(), "振动停止", Toast.LENGTH_SHORT).show();
                break;
                
            //闹铃开始服务
            case R.id.alarm_start_btn:
                long timer = SystemClock.elapsedRealtime() + 5 * 1000;  //设置下一次闹铃的时间,这里定为5秒
                manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timer, pi); //Intent service = new Intent(this, MessageService.class)
                                                                              // PendingIntent pi = PendingIntent.getService(this, 0, service, 0);
                Toast.makeText(getApplicationContext(), "五秒后闹铃显示", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "五秒后闹铃显示");
                break;
            //闹铃暂停服务
            case R.id.alarm_stop_btn:
                Toast.makeText(getApplicationContext(), "闹铃取消", Toast.LENGTH_SHORT).show();
                manager.cancel(pi); //依据pi绑定的intent事件取消闹铃
                break;
                
            //查看手机网络运营商名称
            case R.id.SIM_btn:
                //系统服务-获取机识别码
                TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                //检查是否获取权限,如果没有则调用ActivityCompat.requestPermissions方法
                if (ContextCompat.checkSelfPermission(MainActivity.this,"Manifest.permission.READ_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) {
                    ////123是自定义的,相当于一个标识码,在后面onRequestPermissionsResult回调方法中会用到
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_PHONE_STATE},123); 
                }
                //系获取机识别码
                String msi_code = telManager.getSubscriberId();
                if(msi_code!=null){
                    if(msi_code.startsWith("46000") ||msi_code.startsWith("46002")){//因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号,134/159号段使用了此编号
                        //中国移动
                        Toast.makeText(getApplicationContext(), "中国移动", Toast.LENGTH_SHORT).show();
                    }else if(msi_code.startsWith("46001")){
                        //中国联通
                        Toast.makeText(getApplicationContext(), "中国联通", Toast.LENGTH_SHORT).show();
                    }else if(msi_code.startsWith("46003")){
                        //中国电信
                        Toast.makeText(getApplicationContext(), "中国电信", Toast.LENGTH_SHORT).show();
                    }else if(msi_code.startsWith("")){
                        Toast.makeText(getApplicationContext(), "请授予访问手机识别码权限", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "手机识别码为" + msi_code, Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(this, "请授予访问手机识别码权限", Toast.LENGTH_SHORT).show();
                }
        }
    }

    //第一个参数就是上面申请权限方法需要记住的标识123,第二个参数为你的申请权限的数组,第三个参数是授权回调的结果
    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        if (requestCode == 123) {
            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "请授予访问手机识别码权限", Toast.LENGTH_SHORT).show();
        }
    }

    //参数是一个权限,返回true或false,用户勾选拒绝后不再询问
    public boolean shouldShowRequestPermissionRationale(String permission){
        Toast.makeText(this, "默认权限为拒绝访问", Toast.LENGTH_SHORT).show();
        return false;
    }

}
  • パイでのアラームクラスMessageService.javaを使用する意図を継承しました:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MessageService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), "五秒钟到啦!", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

}

原則と各クラスのメソッドについては、我々は理解することが比較的単純で簡単な記事を書くためにブロガーをお勧めします:
https://www.jianshu.com/p/30edc21c3299

リリース7件のオリジナルの記事 ウォンの賞賛5 ビュー744

おすすめ

転載: blog.csdn.net/qq_44632227/article/details/105233987