This question already has an answer here:
Notifications don't appear
(1 answer)
Closed 2 years ago.
I'm new to programming and app development and I'm trying to develop an app that shows events and notifies the user when a new event is up.I'm trying to create a settings activity with 2 switch buttons, 1 for notifications on status bar and 1 for notification sound. When I turn on the switches, I don't get any notification nor sound.
How can I fix that?
JAVA FILE
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
if (simpleSwitch1.isChecked()){
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
/*
//API level 8
Notification myNotification8 = new Notification(R.drawable.ic_launcher, "this is ticker text 8", System.currentTimeMillis());
Intent intent2 = new Intent(MainActivity.this, SecActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0);
myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2);
manager.notify(11, myNotification8);
*/
}
});}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}
public void onClick(View v) {
simpleSwitch2 = (Switch) findViewById(R.id.simpleswitch2);
String statusSwitch2;
if (simpleSwitch2.isChecked())
notification.defaults |= Notification.DEFAULT_SOUND;
}}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
A couple of stuff here:
For switches, you probably want OnCheckedChangeListener, not
OnClickListener.
You want to set the OnCheckedChangeListener once in your onCreate() and check for the Switch's state
inside this listener:
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// show notification
} else {
// cancel notification
}
}
});`
// Similarly for switch2`
Related
this is my code:
package com.rockykhan.notificationchannels;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class app extends Application {
// MAKING CHANNEL ID'S AS FINAL STRINGS
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW);
channel1.setDescription("this is channel 1");
channel2.setDescription("this is channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
mainActivity:
package com.rockykhan.notificationchannels;
import static com.rockykhan.notificationchannels.app.CHANNEL_1_ID;
import static com.rockykhan.notificationchannels.app.CHANNEL_2_ID;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.Notification;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText title, text;
Button btn_c1, btn_c2;
private NotificationManagerCompat notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title.findViewById(R.id.notificationTitleText);
text.findViewById(R.id.notificationMessageText);
btn_c1.findViewById(R.id.sendNotificationThroughChannel1);
btn_c2.findViewById(R.id.sendNotificationThroughChannel2);
String notificationTitle = title.getText().toString();
String notificationText = text.getText().toString();
notificationManager = NotificationManagerCompat.from(this);
btn_c1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.imp_noti)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
});
btn_c2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_2_ID)
.setSmallIcon(R.drawable.noti)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(2, notification);
}
});
}
}
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">
<Button
android:id="#+id/sendNotificationThroughChannel2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send on channel 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/notificationTitleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Title"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toTopOf="#+id/sendNotificationThroughChannel2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/sendNotificationThroughChannel1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send on channel 1"
app:layout_constraintBottom_toTopOf="#+id/sendNotificationThroughChannel2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/notificationMessageText" />
<EditText
android:id="#+id/notificationMessageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toTopOf="#+id/sendNotificationThroughChannel1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/notificationTitleText" />
</androidx.constraintlayout.widget.ConstraintLayout>
logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rockykhan.notificationchannels/com.rockykhan.notificationchannels.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
So I was trying to send notifications through buttons but the app doesn't seem to start. It crashes and as far as I thought, it was a problem in xml Id's but I can't find the main problem here ( I think it is something to do with the findViewbyId of the editText). Help will be much appreciated!
Assign the result of calling findViewById() to your View variables, don't call findViewById() on the variables itself.
So basically replace these lines
title.findViewById(R.id.notificationTitleText);
text.findViewById(R.id.notificationMessageText);
btn_c1.findViewById(R.id.sendNotificationThroughChannel1);
btn_c2.findViewById(R.id.sendNotificationThroughChannel2);
with these
title = findViewById(R.id.notificationTitleText);
text = findViewById(R.id.notificationMessageText);
btn_c1 = findViewById(R.id.sendNotificationThroughChannel1);
btn_c2 = findViewById(R.id.sendNotificationThroughChannel2);
My app crashing when I try to toggle phone modes. For example when I'm in ring mode end I try to switch on silent is crashing, but when I try to toggle vibrate is working fine. Exactly the same thing is happening when I try to change from vibrate to ring. Check status is working fine, there is not crash.
Here is the logcat line:
at com.example.lab3_1.MainActivity.onSilent(MainActivity.java:56)
That involved the code line:
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Here is the main:
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private AudioManager myAudioManager;
NotificationManager notificationManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new
Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
public void onMode(View v)
{
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_SILENT)
{
Toast.makeText(this,"Now in Silent Mode",Toast.LENGTH_LONG).show();
}
}
public void onRing(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
public void onSilent(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(this,"Now in silent Mode",Toast.LENGTH_LONG).show();
}
public void onVibrate(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
}
Here is the xml file:
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt1"
android:text="CURRENT MODE CHECK"
android:onClick="onMode"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt2"
android:text="RINGER MODE"
android:onClick="onRing"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt3"
android:text="SILENT MODE"
android:onClick="onSilent"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt4"
android:text="VIBRATE MODE"
android:onClick="onVibrate"/>
</LinearLayout>
I'm a beginner programmer and I'm working on an app where I want to have a Settings activity with 2 switch buttons (one to turn on/off notifications in status bar and one to turn on/off notification sound).Yesterday everything went fine with the compiling but today suddenly I got all these errors about not resolving some methods or symbols. What happened and how can I fix it?
In particular the errors where the following:
cannot resolve method: onCreate,setContentView,getSystemService, findViewById
cannot resolve symbol: OnCheckedChangeListener, simpleswitch1, simpleswitch2, arg0, view
Override: Annotations are not allowed here
onClick and onCheckedChanged do not work properly.
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new View.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onCheckedChanged(CompoundButton simpleswitch1, boolean isChecked) {
if (isChecked) {
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}});
public void onClick(View view) {
public void onCheckedChanged(CompoundButton simpleswitch2, boolean isChecked) {
if (isChecked){
notification.defaults |= Notification.DEFAULT_SOUND;
}}}}}
XML File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
From you java you are placing methods inside other methods this is not possible in java
Also
Try setting listeners as such
// set default state on/off
simpleSwitch1.setChecked(false);
simpleSwitch2.setChecked(false);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
simpleSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
hope this helps, your java code was quite hard to understand.
I'm making a bluetooth application using android studio and the problem is that the application scans for devices once only. After it finds a device, it stops looking for other.I want to search for all available devices around my device. The activity code is:
package com.example.yubrajsharma.my_application;
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.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import static android.view.View.INVISIBLE;
public class MainActivity extends AppCompatActivity{
BluetoothAdapter mBluetoothAdapter;
int count;
Button lister;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
String[] mBTDevice;
ArrayAdapter<String> adapter;
private static final String TAG = "MainActivity";
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
unregisterReceiver(mReciever);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.INVISIBLE);
Button searchbtn = (Button) findViewById(R.id.searchbtn);
Button lister = (Button) findViewById(R.id.lists);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter.isEnabled()){
lister.setVisibility(View.VISIBLE);
}
lister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listdata();
}
});
}
private BroadcastReceiver mReciever = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
}
count = mBTDevices.size();
int j = 0;
mBTDevice = new String[count];
if(count>0) {
for (BluetoothDevice device : mBTDevices) {
mBTDevice[j] = device.getName();
j++;
}
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
else{
mBTDevice[0] = "no devices found";
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
mBluetoothAdapter.cancelDiscovery();
pg.setVisibility(View.INVISIBLE);
Log.d(TAG, "Disabled");
}
};
private void listdata() {
if(mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.VISIBLE);
IntentFilter infill = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReciever, infill);
}
public void enableDisableBT(View view) {
Button lister = (Button) findViewById(R.id.lists);
if(!mBluetoothAdapter.isEnabled()){
Intent enableBTintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTintent);
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
if(mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
}
}
The Code for the xml file is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.yubrajsharma.my_application.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<Button
android:id="#+id/lists"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:visibility="invisible"
app:layout_constraintLeft_toRightOf="#+id/searchbtn"
app:layout_constraintBottom_toBottomOf="#+id/searchbtn"
android:layout_marginRight="28dp"
android:layout_marginEnd="28dp"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/paired"
android:layout_alignEnd="#+id/paired" />
<Button
android:id="#+id/searchbtn"
android:onClick="enableDisableBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON/OFF"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="3dp" />
<ListView
android:id="#+id/paired"
android:layout_width="368dp"
android:layout_height="422dp"
app:layout_constraintTop_toBottomOf="#+id/lists"
app:layout_constraintLeft_toLeftOf="#+id/searchbtn"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginEnd="29dp"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/lists"
android:layout_toStartOf="#+id/lists"
tools:visibility="invisible" />
</RelativeLayout>
How to scan all the available devices?
Well in your BroadcastReceiver.onReceive method once it gets called you call:
mBluetoothAdapter.cancelDiscovery();
So this stops the discovering process. Try to remove this line and see what happens.
However keep in mind the following from the official documentation:
Because discovery is a heavyweight procedure for the Bluetooth
adapter, this method should always be called before attempting to
connect to a remote device with connect(). Discovery is not managed by
the Activity, but is run as a system service, so an application should
always call cancel discovery even if it did not directly request a
discovery, just to be sure.
I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.