I'm constantly getting a security exception when trying to launch a different activity other than my MainActivity, code works fine when i'm launching my MainActivity but throws an exception when I try to launch any other activity other than MainActivity, I've been looking for answers and got a solution to put -android:exported="true"- in my Manifest, however this doesn't help the problem i'm facing, any help so far will be highly appreciated.
Manifest file for launching MainActivity - (Which works)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.infamuspips.cess">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:exported="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"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".registration"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_name"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_securityquestions"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_id"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_cellnumber"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_email"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_password"
android:label="#string/app_name"></activity>
<activity
android:name=".Maindrawer"
android:label="#string/title_activity_maindrawer"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
.
Manifest file for launching registration Activity - (Which don't work)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.infamuspips.cess">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:exported="true"
android:theme="#style/AppTheme">
<activity android:name=".registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_name"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_securityquestions"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_id"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_cellnumber"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_email"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_password"
android:label="#string/app_name"></activity>
<activity
android:name=".Maindrawer"
android:label="#string/title_activity_maindrawer"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
.
Here's my MainActivity Class
package com.infamuspips.cess;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.suitebuilder.annotation.Suppress;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Encryption";
EditText editText,username,password;
Button button;
TextView cancel,forgot_password;
static String Username = null;
static String PassWord = null;
static String GetUsername = null;
static String GetPassword = null;
SecretKey secretKey;
String cipherText, decryptedText;
KeyGenerator keyGen;
Cipher aesCipher;
FileOutputStream fos;
byte[] byteDataToEncrypt, byteCipherText, byteDecryptedText;
TextWatcher textwatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String User = username.getText().toString();
String Pass = password.getText().toString();
if (!User.isEmpty() && !Pass.isEmpty()) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
editText = (EditText) findViewById(R.id.editText);
username.addTextChangedListener(textwatcher);
password.addTextChangedListener(textwatcher);
button = (Button) findViewById(R.id.logIn);
cancel = (TextView) findViewById(R.id.LoginCancel);
forgot_password = (TextView) findViewById(R.id.forgot_password);
//Set Clickable attributes
cancel.setClickable(true);
button.setEnabled(false);
editText.setEnabled(false);
//Call Operation Methods
username.requestFocus();
//Cancel();
//Forgot_Password();
Log_In();
}
private void Cancel(){
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),registration.class);
startActivity(i);
}
});
}
private void Forgot_Password(){
forgot_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
class PerformBackGround extends AsyncTask<Void, Void, String>{
private ProgressDialog mDialog;
public PerformBackGround() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setProgress(0);
mDialog.setMax(10);
mDialog.setCancelable(false);
mDialog.show();
}
#Override
protected String doInBackground(Void... params) {
try{
String link = "http://*************************";
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result = bufferedReader.readLine();
return result;
}catch (Exception e){
return "Exception" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
String response;
if (jsonStr != null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String User = jsonObj.get("name").toString();
String Password = jsonObj.get("surname").toString();
mDialog.cancel();
if (User.equals(Username) && Password.equals(PassWord)){
//String name = jsonObj.get("name").toString();
//String Surname = jsonObj.get("surname").toString();
response = jsonObj.get("surname").toString();
getResponse(response);
Intent i = new Intent(getApplicationContext(),Maindrawer.class);
startActivity(i);
}else{
response = "invalid";
getResponse(response);
}
}catch (Exception e){
mDialog.cancel();
e.printStackTrace();
response = "unable";
getResponse(response);
}
}else{
mDialog.cancel();
response = "unconnect";
getResponse(response);
}
}
}
private void Log_In(){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//PerformBackGround bg = new PerformBackGround();
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
String user = username.getText().toString();
String pass = password.getText().toString();
Username = user;
PassWord = pass;
//addmodules addm =new addmodules();
//addm.execute();
Toast.makeText(MainActivity.this, md5(username.getText().toString()), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),Maindrawer.class);
startActivity(i);
username.getText().clear();
password.getText().clear();
}
});
}
public String md5(String text) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(text.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
}
Here's my registration Activity - (Which doesn't launch & throws an exception
)
package com.infamuspips.cess;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Rebone on 4/24/2016.
*/
public class registration extends AppCompatActivity {
EditText up, firstname, MidName, lastName,Email,id,password, confirmpassword;
Button logIn, Register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
up = (EditText) findViewById(R.id.editText1);
logIn = (Button) findViewById(R.id.reg_login);
Register = (Button) findViewById(R.id.reg_register);
up.setEnabled(false);
Register.setEnabled(true);
LogIn();
Register();
}
public void LogIn() {
logIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
public void Register() {
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String initial = "Nothing";
//Modified
Intent a = new Intent(v.getContext(),reg_name.class);
//Intent a = new Intent(v.getContext(),reg_password.class);
a.putExtra("Results", initial);
startActivity(a);
}
});
}
}
-
And here's the full stack trace
08-09 13:59:52.444 220-10439/? W/ActivityManager: mDVFSLock.acquire()
08-09 13:59:52.444 220-10439/? W/ActivityManager: Permission denied: checkComponentPermission() owningUid=10118
08-09 13:59:52.444 220-10439/? W/ActivityManager: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.infamuspips.cess/.registration } from null (pid=13769, uid=2000) not exported from uid 10118
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityStack.startActivityLocked(ActivityStack.java:2498)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityStack.startActivityMayWait(ActivityStack.java:3095)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:2298)
08-09 13:59:52.460 220-10439/? W/System.err: at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:147)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:1603)
08-09 13:59:52.460 220-10439/? W/System.err: at android.os.Binder.execTransact(Binder.java:338)
08-09 13:59:52.460 220-10439/? W/System.err: at dalvik.system.NativeStart.run(Native Method)
Replace
<activity android:name=".registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
with
<activity android:name="com.infamuspips.cess.registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Clean and rebuild your project
Related
I'm trying to implement an app that allows me to record the audio of calls, activating the service via a toggle button. I can't figure out what is wrong with my code as once I set the toggle button to ON and initiate the call, there is no file saved.
I don't understand if the problem is in saving (maybe I'm looking for the file in the wrong directory?), Or in the fact that it doesn't actually record.
I'm using AndroidStudio 4.0 and i'm trying my app on my Samsung S9.
Thanks in andvance for helping !
RecordService.java
package com.example.registrachiamate;
import android.app.MediaRouteButton;
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class RecordService extends Service {
private MediaRecorder rec;
private File file;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
file= Environment.getExternalStorageDirectory();
Date date=new Date();
CharSequence sdf= DateFormat.format("MM-dd-yy-hh-mm--ss",date.getTime());
rec=new MediaRecorder();
rec.setAudioSource(MediaRecorder.AudioSource.MIC);
rec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
rec.setOutputFile(file.getAbsolutePath()+"/"+sdf+"rec.3gp");
rec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
TelephonyManager manager=(TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
assert manager != null;
manager.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String phoneNumber) {
//super.onCallStateChanged(state, phoneNumber) {
if (TelephonyManager.CALL_STATE_IDLE==state){
rec.stop();
rec.reset();
rec.release();
stopSelf();
}else if(TelephonyManager.CALL_STATE_OFFHOOK==state && rec==null){
try {
rec.prepare();
} catch (IOException e) {
e.printStackTrace();
}
rec.start();
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
return START_STICKY;
}
}
ActivityButton1.java
package com.example.registrachiamate;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
public class ActivityButton1 extends AppCompatActivity {
ToggleButton startandoff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button1);
startandoff=(ToggleButton)findViewById(R.id.toggleButton);
}
public void tooglebutton(View view)
{
boolean checked=((ToggleButton)view).isChecked();
if (checked){
Intent intent=new Intent(this,RecordService.class);
startService(intent);
Toast.makeText(getApplicationContext(),"Call Record STARTED",Toast.LENGTH_SHORT).show();
}else {
Intent intent=new Intent(this,RecordService.class);
stopService(intent);
Toast.makeText(getApplicationContext(),"Call Record STOPPED",Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml, if i put the RecordService, in it stops running
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.registrachiamate">
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.PHONE_STATE"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityButton1"></activity>
<activity android:name=".ActivityButton2"></activity>
<activity android:name=".ActivityButton3"></activity>
<activity android:name=".ActivityButton4"></activity>
<activity android:name=".RecordService"></activity>
</application>
</manifest>
I'm not sure what is going on. I click the button to take the image and my app closes.
I'm attempting to make an app to capture and use an image. I haven't even been able to capture the image.
I get the following message in log cat:
FATAL EXCEPTION: main
Process: com.example.fixmyphysics, PID: 23526
java.lang.IllegalArgumentException: Missing android.support.FILE_PROVIDER_PATHS meta-data
at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:613)
at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
at com.example.fixmyphysics.MainActivity.dispatchPictureTakerAction(MainActivity.java:67)
at com.example.fixmyphysics.MainActivity.access$000(MainActivity.java:27)
at com.example.fixmyphysics.MainActivity$1.onClick(MainActivity.java:44)
at android.view.View.performClick(View.java:7356)
at android.widget.TextView.performClick(TextView.java:14230)
at android.view.View.performClickInternal(View.java:7322)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27804)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7073)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
MainActivity.java
package com.example.fixmyphysics;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.os.Environment.getExternalStoragePublicDirectory;
public class MainActivity extends AppCompatActivity {
Button picture_btn;
ImageView display;
String pathToFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picture_btn = findViewById(R.id.capture_image);
if (Build.VERSION.SDK_INT >=23){
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
picture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchPictureTakerAction();
}
});
display = findViewById(R.id.imageView4);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap imageBitmap = BitmapFactory.decodeFile(pathToFile);
display.setImageBitmap(imageBitmap);
}
}
private void dispatchPictureTakerAction(){
Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) !=null){
File photoFile = null;
photoFile = createImageFile();
if (photoFile != null){
pathToFile = photoFile.getAbsolutePath();
Uri photoURI = FileProvider.getUriForFile(MainActivity.this, "com.fixmyphysics.FileProvider", photoFile);
takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePic, 1);
}
}
}
private File createImageFile() {
String name = new SimpleDateFormat("yyyyMMdd__HHmmss").format(new Date());
File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile(name,".jpg", storageDir);
} catch (IOException e){
Log.d("mylog", "Excep : " + e.toString());
}
return image;
}
}
AndroidMainifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fixmyphysics">
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<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>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
</application>
</manifest>
Try this one.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />`enter code here`
Hope You all having a good day, I am learning android and i'm creating an application that scans for Wifi networks. The code makes sense and i seem to have the permissions correctly yet no permissions are being requested at all. Could you help me to figure out why aren't the permissions being granted? Am I missing anything ? Here is my code:
main activity.java:
package com.example.x.wifilocator;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private StringBuilder sb = new StringBuilder();
private TextView tv;
List<ScanResult> scanList;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView)findViewById(R.id.txtWifiNetworks);
checkpermission();
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkpermission() {
int hasWiFi = checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE);
if (hasWiFi != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.ACCESS_WIFI_STATE},
REQUEST_CODE_ASK_PERMISSIONS);
Toast.makeText(this,"No Permission",Toast.LENGTH_LONG);
}
getWifiNetworksList();
}
private void getWifiNetworksList(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);;
registerReceiver(new BroadcastReceiver(){
#SuppressLint("UseValueOf") #Override
public void onReceive(Context context, Intent intent) {
sb = new StringBuilder();
scanList = wifiManager.getScanResults();
sb.append("\n Number Of Wifi connections :" + " " +scanList.size()+"\n\n");
for(int i = 0; i < scanList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append((scanList.get(i)).toString());
sb.append("\n\n");
}
tv.setText(sb);
}
},filter);
wifiManager.startScan();
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<!--Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<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>
</application>
</manifest>
Thanks in advance for your efforts.
I have added the ITelephony.aidl file in the src folder with the package name as package com.android.internal.telephony. The below code is the PhoneCallStateListener.java
package com.broad.sowmy.blockingcall;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
/**
* Created by sowmy on 24-10-2016.
*/
public class PhoneCallStateListener extends PhoneStateListener {
private Context context;
String block_num;
SharedPreferences shared;
public PhoneCallStateListener(Context context){
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
shared=context.getSharedPreferences("get",Context.MODE_PRIVATE);
block_num=shared.getString("number",null);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Toast.makeText(context, block_num, Toast.LENGTH_SHORT).show();
Class clazz = Class.forName(tm.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(tm);
System.out.println("Call " + block_num);
if (incomingNumber.equalsIgnoreCase("+91" + block_num)) {
telephonyService = (ITelephony) method.invoke(tm);
telephonyService.silenceRinger();
System.out.println(" in " + block_number);
telephonyService.endCall();
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
//Turn OFF the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
case PhoneStateListener.LISTEN_CALL_STATE:
}
super.onCallStateChanged(state, incomingNumber);
}
}
PhoneCallReceiver.java is below
package com.broad.sowmy.blockingcall;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
/**
* Created by sowmy on 24-10-2016.
*/
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneCallStateListener phoneCallStateListener=new PhoneCallStateListener(context);
tm.listen(phoneCallStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
Mainfest file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broad.sowmy.blockingcall">
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<receiver android:name=".PhoneCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
And in ITelephony.aidl
package com.android.internal.telephony;
public interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
Make com/android/internal/telephony folder structure inside src folder and put ITelephony.aidl file inside the telephony folder.
I have an app with 2 classes, I need my app to open the second class CardActivity when the NFC tag tapped/swiped. The app opens fine, but MainActivity is run, instead of CardActivity.
I would hazard a guess that this is an issue with my manifest, but it looks correct. Here it is regardless:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm confident the tag itself is correct, as I have opened it in another app to view it's contents.
Below are the two classes.
CardActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.bluetooth.*;
public class CardActivity extends Activity implements OnClickListener {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_activity);
// see if app was started from a tag and show game console
Intent intent = getIntent();
Log.e(TAG, "Hello world. Intent Type: "+ intent.getType());
if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord = msg.getRecords()[0];
String payload = new String(cardRecord.getPayload());
turnBluetoothOn(payload);
}
}
private void turnBluetoothOn(String payload) {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage(payload);
builder.setIcon(android.R.drawable.ic_dialog_alert);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
android.os.Process.killProcess(android.os.Process.myPid());
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
MainActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the code I used to write the tag. This is done on a different app incidentally:
NdefRecord appRecord = NdefRecord.createApplicationRecord("com.spotsofmagic.spotsofmagic");
// record that contains our custom "retro console" game data, using custom MIME_TYPE
byte[] payload = getPayload().getBytes();
byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII"));
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes,
new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord});
// Some code here removed for readability
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
Does the NDEF message on the tag contain an Android Application Record? That could explain how MainActivity is launched. However, that can only be the cause if the AAR is the first record of the NDEF message on the tag or if the first record does not match the intent filter.