int value passed with intents doesn't change second time despite onNewIntent() - android-studio

I pass an integer value (guide) to the next class(activity) like this:
in different activities.. first:
public void onClick(View v) {
Intent intent002a = new Intent(getApplicationContext(), GameOver002a.class);
intent002a.putExtra("guide", 11001001);
startActivity(intent002a);
}
second:
public void onClick(View v) {
Intent intent003a = new Intent(getApplicationContext(), GameOver002a.class);
intent003a.putExtra("guide", 11002001);
startActivity(intent003a);
}
and so on..
Then I receive the intent:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game_over002a);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
super.onStart();
UnityAds.changeActivity(this);
UnityAds.init( this, "*******", this);
UnityAds.setDebugMode(true);
UnityAds.setTestMode(true);
TextView neinTextView = (TextView) findViewById(R.id.nein_textview002a);
if (neinTextView != null) {
neinTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
});
}
TextView jatextview = (TextView) findViewById(R.id.ja_textview002a);
if (jatextview != null) {
jatextview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(GameOver002a.this)
.setMessage("Watch a short ad to continue at the last checkpoint?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
if (UnityAds.setZone("rewardedVideo") && UnityAds.canShow()) {
UnityAds.show();
}}
}).create().show();
}
});
}
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(R.string.zurück_zum_menü_frage)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
}).create().show();
}
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onVideoStarted() {
}
#Override
public void onVideoCompleted(String s, boolean b) {
levelAuswahl();
}
#Override
public void onFetchCompleted() {
}
#Override
public void onFetchFailed() {
TextView jatextview = (TextView) findViewById(R.id.ja_textview002a);
if (jatextview != null) {
jatextview.setText(R.string.videoladen_fail);
jatextview.setClickable(false);
}
}
#Override
public void onResume()
{
super.onResume();
UnityAds.changeActivity(this);
onNewIntent(getIntent());
}
public void levelAuswahl() {
int guide;
guide = getIntent().getIntExtra("guide",0);
if (guide == 11001001) {
Intent intent = new Intent(getApplicationContext(), Story001a.class);
startActivity(intent);
}else if (guide == 11002001) {
Intent intent = new Intent(getApplicationContext(), Story002b.class);
startActivity(intent);
}else if (guide == 11007001) {
Intent intent = new Intent(getApplicationContext(), Story004a.class);
startActivity(intent);
} else {
Intent intent = new Intent(getApplicationContext(), Startbildschirm.class);
startActivity(intent);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
}
to choose the right activity.. EVERY PART OF THE STORY HAS HIS OWN ACTIVITY
following scenario:
I start the app and fail at the Story002a activity .. then I pass an integer value (guide) with an intent .. After watching an ad succesful the method levelAuswahl() is called (level chooser). it receives the intent and takes the right if clause and I start again at Story001.. THIS PART WORKS CORRECT
BUT.. if I fail at Story003a the value guide is passed with an intent exact as in Story002a..but this time in the the same activitie opens although I use onNewIntent()..
what do I need to change? Any ideas?
Thanks in advance!
here is the manisfest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name=".Startbildschirm"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Tutorial"
android:screenOrientation="landscape"/>
<activity android:name=".Support"
android:screenOrientation="landscape"/>
<activity android:name=".GameOver"
android:screenOrientation="landscape"/>
<activity android:name=".Story001a"
android:screenOrientation="landscape"/>
<activity android:name=".Story002a"
android:screenOrientation="landscape"/>
<activity android:name=".Story002b"
android:screenOrientation="landscape"/>
<activity android:name=".Story003a"
android:screenOrientation="landscape"/>
<activity android:name=".Story003b"
android:screenOrientation="landscape"/>
</application>

getIntent() returns the Intent that the Activity was started with (ie: the one that caused onCreate() to be called. If you are returning to an existing instance of GameOver, and onCreate() is not being called, then you will get the new Intent delivered in onNewIntent(). The Intent passed to onNewIntent() should contain the correct extra value.
If this is not your case, please give more details about your situation.

Instead of using
android:launchMode="singleTask" //or singleTop
is used
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
and everything works fine
use onNewIntent() like this to get your new intent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}

Related

Broadcast Reciever ACTION_SHUTDOWN Intent is not working in Android version 11

Foreground service class code for calling the shutDown broadcast receiver.
public class SmsForegroundService extends Service{
private BroadcastReceiver receiver;
public static class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
Log.d(TAG, "onReceive: "+intent.getAction());
if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
Log.d(TAG, "onReceive: ScreenOff");
}
}
// constructor
public MyReceiver(){
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
receiver = new MyReceiver();
this.registerReceiver(receiver,filter);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: service destroyed");
super.onDestroy();
this.unregisterReceiver(receiver);
}
//
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG ,"service running");
final String CHANNEL_ID = "foreground Service ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentText("Service is running")
.setContentTitle("Service is enabled")
.setSmallIcon(R.drawable.ic_launcher_background);
startForeground(1001, notification.build());
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return null;
}
}
AndroidManifest file, here I added only the permission for Foreground services, I think there is no other permission is required for action_shutdown in manifest for versions greater than Oreo.
<?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.mywork.smsbroadcast">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<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/Theme.SmsBroadcast">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".SmsForegroundService">
</service>
</application>
</manifest>
MainActivity I have called the service class inside on Create method MainActivity class.
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!foregroundServiceRunning())
{
Intent serviceIntent = new Intent(this, SmsForegroundService.class);
ContextCompat.startForegroundService(this,serviceIntent);
}
}
public boolean foregroundServiceRunning(){
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo serviceInfo: activityManager.getRunningServices(Integer.MAX_VALUE)){
if(SmsForegroundService.class.getName().equals(serviceInfo.service.getClassName())){
return true;
}
}
return false;
}
}

Encrypt Bluetooth Chat

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<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=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

Action_Call permission not granted in Android Studio

I am trying to make an app which can directly call if the number is entered but the permission is not granted and hence no call is made...
I have requested permission in AndriodManifest.xml
Everytime I enter a number, "Hello" pops up which is written if Granted is Not Granted.
My code:
MainActivity.java
package com.example.block9;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void redirectmessage(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
String message = (((EditText) findViewById(R.id.textmessage)).getText()).toString();
Uri num = Uri.parse("smsto:" + number);
Intent smsIntent = new Intent(Intent.ACTION_SENDTO, num);
smsIntent.putExtra("sms_body", message);
startActivity(smsIntent);
}
public void redirectcall(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
Toast t = null;
//t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
return;
}
startActivity(callIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.block9">
<uses-permission android:name="android.permission.CALL_PHONE"/>
<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>
Any Help would be Appreciated!!`enter code here.
If your Target Device API is <22 then you don't need to ask for permission as the permission will automatically provide But as a Developer you have to ready for every possibility. in case if target device API is >=23 then you have to manually request the permission. For more information on this Read this
public void redirectcall(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
Toast t = null;
//t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
grantPermission();
return;
}
startActivity(callIntent);
}
private void grantPermission() {
// show your dialog box to ask for permission
new AlertDialog.Builder(this)
.setTitle("Call Permission Required")
.setMessage("This App needs Call permission, to function properly")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
.show();
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//here permission will be given
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 3); // 3 is requestCode and can be any number
}
})
.create()
.show();
}
After Making a Request Now, we will call #Override method onRequestPermissionsResult() to handle the scenario of Rejected or accepted Request
*#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 3: //remember that 3 is the same number which we specified while requesting
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// Call-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
redirectcall();
}
}else{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}*
Full MainActivity.java code is here: https://gist.github.com/Shoaibpython/eda5394ee4bc441396d68d5ef603cd3
Please consider replying here if you saw any error.

Android Studio Bluetooth startDiscovey not working

In my code, after I run startDiscovery().
Nothing seems to happen and I don't know why.
As #Mitch suggest, I changed back to using button to do startDiscovery.
But now it seems worse as it crashes right after I press the button.
public class BTActivity extends AppCompatActivity{
private static final String TAG = "BTActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
private EcgView mEcgView;
//Create a BroadcastReceiver for
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BTAdapter.ACTION_STATE_CHANGED)){
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BTAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG,"onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG,"onReceive: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG,"onReceive: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG,"onReceive: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)){
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode){
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Enabled");
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Able to receive connection");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Not able to receive connection");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG,"mBroadcastReceiver2: Connecting");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG,"mBroadcastReceiver2: Connected");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3cases:
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDED");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDING");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE){
Log.d(TAG, "BroadcastReceiver: BOND_NONE");
}
}
}
};
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.enabledisable:
//if BT is enable, turn it off; if not then prompt user to enable BT;
if (!BTAdapter.getDefaultAdapter().isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(BTAdapter.getDefaultAdapter().isEnabled()) {
BTAdapter.getDefaultAdapter().disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
return true;
case R.id.enablediscoverable:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(BTAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2, intentFilter);
return true;
case R.id.discover:
Intent intent = new Intent(getApplicationContext(),SearchActivity.class);
startActivity(intent);
/*
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
*/
return true;
default:
return false;
}
}
/*
private void checkBTPermissions() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK Version < LOLLIPOP");
}
}
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,filter);
//lvNewDevices.setOnItemClickListener(BTActivity.this);
//Check if the phone support BT
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter == null) {
//System.exit(0);
}
//mConnectThread = new ConnectThread(mDevice);
//mConnectThread.start();
mEcgView = (EcgView) findViewById(R.id.ecgView);
}
public void toMainActivity(View view){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
So after the click on the Search Devices from the action bar, the app will go to another activity. But when I click on Start Searching in that activity, the app crashes. Don't know why as logic should be the same.
public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "SearchActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
lvNewDevices.setOnItemClickListener(SearchActivity.this);
}
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
public void btnDiscover(View view){
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
}
public void backToBT(View view){
Intent intent = new Intent(getApplicationContext(),BTActivity.class);
startActivity(intent);
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Cancel Discovery as it's costly
BTAdapter.cancelDiscovery();
Log.d(TAG,"onItemClick:Clicked a Device");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG,"onItemClick: Device Name: " + deviceName);
Log.d(TAG,"onItemClick: Device Address " + deviceAddress);
//Bonding
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
And the manifest is attached
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ted.pawan462">
<user-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<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>
<activity android:name=".BTActivity" />
<activity android:name=".SearchActivity"></activity>
</application>
</manifest>
This is the Logcat
1-07 21:40:39.633 32744-367/com.example.ted.pawan462 I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (Ia6c73e7530)
OpenGL ES Shader Compiler Version: E031.29.00.00
Build Date: 12/04/15 Fri
Local Branch: mybranch17080070
Remote Branch: quic/LA.BF.1.1.3_rb1.5
Local Patches: NONE
Reconstruct Branch: NOTHING
01-07 21:40:39.635 32744-367/com.example.ted.pawan462 I/OpenGLRenderer: Initialized EGL, version 1.4
01-07 21:40:41.786 32744-32744/com.example.ted.pawan462 I/ListPopupWindow: Could not find method setEpicenterBounds(Rect) on PopupWindow. Oh well.
01-07 21:40:41.812 32744-32744/com.example.ted.pawan462 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
01-07 21:43:54.309 32744-367/com.example.ted.pawan462 D/OpenGLRenderer: endAllStagingAnimators on 0x9db76280 (MenuPopupWindow$MenuDropDownListView) with handle 0x9d2784b0
01-07 21:43:55.320 32744-32744/com.example.ted.pawan462 D/SearchActivity: Looking for unpaired devices
01-07 21:43:55.327 32744-32744/com.example.ted.pawan462 D/AndroidRuntime: Shutting down VM
01-07 21:43:55.329 32744-32744/com.example.ted.pawan462 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ted.pawan462, PID: 32744
Theme: themes:{default=overlay:com.wsdeveloper.galaxys7, iconPack:com.wsdeveloper.galaxys7, fontPkg:com.wsdeveloper.galaxys7, com.android.systemui=overlay:com.wsdeveloper.galaxys7, com.android.systemui.navbar=overlay:com.wsdeveloper.galaxys7}
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21158) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5461) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isDiscovering()' on a null object reference
at com.example.ted.pawan462.SearchActivity.btnDiscover(SearchActivity.java:58)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21158) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5461) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I think I might have made it worse.
The only thing that stands out to me is you have checkBTPermissions() commented out. But I'm assuming you've tried uncommenting that.
Also make sure that your other devices are set to "discoverable" or the phone won't be able to see them.
Other than that I think it looks pretty good. Maybe something weird going on because your using a menu? Not sure :(.

I can't see the three vertical dots in my emulator action bar on Android Studio

Hi everyone so I'm kind of new to all of this, and my instructor has some extra code inside of the home class as well as three vertical dots inside of the action bar. He is doing stuff with it and I am not able to catch up because all I have in the action bar is the name of my project. Any help would be appreciated. Here is my code:
package com.example.gamee.taskit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list);
mItems[0] = new Task();
mItems[0].setName("Task 1");
mItems[0].setUpdatedDate("NULL");
mItems[1] = new Task();
mItems[1].setName("Task 2");
mItems[1].setUpdatedDate("NULL");
mItems[2] = new Task();
mItems[2].setName("Task 3");
mItems[2].setUpdatedDate("NULL");
mItems[3] = new Task();
mItems[3].setName("Task 4");
mItems[3].setUpdatedDate("NULL");
for (Task items : mItems) {
items.setDate(new Date());
}
mAdapter = new TaskAdapter(mItems);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(mAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mTaskLocation = position;
Task task = mItems[position];
task.setPosition(position);
Intent i = new Intent(TaskListActivity.this, SetTaskActivity.class);
i.putExtra(EXTRA, task);
startActivityForResult(i, REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mUpdatedTask = (Task) data.getSerializableExtra(SetTaskActivity.EXTRA2);
mItems[mTaskLocation] = mUpdatedTask;
Task task = new Task();
mAdapter.notifyDataSetChanged();
}
private class TaskAdapter extends ArrayAdapter<Task> {
TaskAdapter(Task[] tasks) {
super(TaskListActivity.this, R.layout.tak_list_row, R.id.view, tasks);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
TextView dateView = (TextView) convertView.findViewById(R.id.dateView);
Task task = getItem(position);
if (task.getUpdatedDate().equals("NULL")) {
dateView.setText("No Date Selected");
} else {
dateView.setText(task.getUpdatedDate());
SetTaskActivity.sChecker = false;
}
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkitycheck);
checkBox.setChecked(task.isDone());
return convertView;
}
}
}
Also here is my Android manifest. Not exactly sure what an Android manifest is to be honest, but when I looked at an error it mentioned it.
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".TaskListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".SetTaskActivity">
</activity>
</application>

Resources