マツリさんの日記

androidプログラミング初心者の奮闘日記です。たまに統計学もしてます。

許可ダイアログの表示

 android6.0(marshmallow)以降では、permissionについて明示的な許可が必要になります。googleのdeveloper向けのサイトを元に、不完全なのですが、このように許可を作ってみました。stackoverflowには独自メソッドをつくるやり方もあったのですが・・・

 

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS) || ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}

 

  最初に公開してきた時から、色々と変更していますので、あらためて一部のクラスを自分の備忘録として書いておきます。

 

 MainActivity.java

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 10;

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}
}
}

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

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS) || ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}

Button instructionButton = (Button) findViewById(R.id.instruction);
assert instructionButton != null;
instructionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), Instruction.class);
startActivity(intent);
}
});

Button instruction2Button = (Button) findViewById(R.id.instruction2);
assert instruction2Button != null;
instruction2Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), Instruction2.class);
startActivity(intent);
}
});

Button instruction3Button = (Button) findViewById(R.id.instruction3);
assert instruction3Button != null;
instruction3Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), Instruction3.class);
startActivity(intent);
}
});

Button instruction4Button = (Button) findViewById(R.id.instruction4);
assert instruction4Button != null;
instruction4Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), Instruction4.class);
startActivity(intent);
}
});

PackageInfo packageInfo = null;
TextView textView = (TextView)findViewById(R.id.version);
try {
packageInfo = getPackageManager().getPackageInfo("com.rnma2ri.saftyapp", PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
assert textView != null;
assert packageInfo != null;
textView.setText("versionCode : "+packageInfo.versionCode+" / "+"versionName : "+packageInfo.versionName);
}
}

MyDialog.java

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;

import java.util.ArrayList;
import java.util.List;

public class MyDialog extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_my_dialog);

List<String> list = new ArrayList<String>();
list.add("風邪で声が変わったは詐欺!");
list.add("電話番号が変わったは詐欺!");
list.add("医療費還付金があるは詐欺!");
list.add("詐欺の電話に注意しましょう!");
final CharSequence[] charSequences = list.toArray(new String[list.size()]);
AlertDialog.Builder alert = new AlertDialog.Builder(this, R.style.Theme_AppCompat_DialogActivity);
alert.setTitle(R.string.dialog_title)
.setIcon(R.mipmap.btn1)
.setItems(charSequences, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int item) {
String string = charSequences[item].toString();
}
})
.setPositiveButton(R.string.dialog_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MyDialog.this.finish();
}
});
alert.create().show();
}
}

PhoneReceiver.java

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

class PhoneReceiver extends PhoneStateListener {
private int totalCount = 0;
private Context context;

PhoneReceiver(Context context) {
this.context = context;
}

// 通話状態の変化に応じて表示を変更する
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);

switch (state) {
// 着信時の処理内容
case TelephonyManager.CALL_STATE_RINGING:

// ContentResolverを使って、端末内の番号を取得し、着信中の番号と突き合わせる
Cursor addressTable = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
try {
if (addressTable != null) {
while (addressTable.moveToNext()) {
String phoneNumber = addressTable.getString(addressTable.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
for (int i = 0; i < addressTable.getCount(); i++) {
int count = BooleanSum(PhoneNumberUtils.compare(phoneNumber, incomingNumber));
totalCount += count;
}
}
}
} finally {
assert addressTable != null;
addressTable.close();
}
if (totalCount < 1) {
Intent i = new Intent(context.getApplicationContext(), MyDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(i);
}
break;
}
}

// PhoneNumberUtilメソッドのBoolean型の戻り値をint型(0 or 1)に変換するメソッド
private int BooleanSum(Boolean exchanger) {
if (exchanger) return 1;
else {
return 0;
}
}
}

PhoneStateReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneStateReceiver extends BroadcastReceiver {
// 各フィールドの定義
TelephonyManager manager;
PhoneReceiver phoneStateListener;
static boolean listener = false;

// intent情報を処理する
@Override
public void onReceive(Context context, Intent intent) {
// PhoneReceiverインスタンスの生成
phoneStateListener = new PhoneReceiver(context);
// TelephonyManagerインスタンスの生成
manager =((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE));

if(!listener) {
manager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
listener = true;
}
}
}

 MainActivity.javaの最後では、versioncodeを表示するようにしています。

 まだまだ不完全ですが、一応これでひと段落です。間違いや効率的なやり方があれば教えていただけると助かります。