I have a really bad problem.
I have one notification service which works fine. When I test it works just fine I turn off/on 10 times to see if service failed or return null but it works fine. I also close application many time to see if its return null but it works fine.
but sometimes when I'm using my phone application show force close such as when I'm using other apps, crash system of firebase say getaction or intent is null.
What am I doing wrong?
crash system
this is my service code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sp = getSharedPreferences("accdata", Context.MODE_PRIVATE);
namesaveget = sp.getString("nameacc","No Account");
int getwhattodo = intent.getIntExtra("service_call",0);
if (intent == null || intent.getAction() == null || getwhattodo == 0) {
Log.e("receiver","service faild");
Crashlytics.log("service faild to call");
if (getwhattodo == 0) {
stopSelf();
}
}
if (intent != null && getwhattodo == 2) {
Log.e("receiver","call done");
createNotificationChannel();
showMainNotification();
showSubNotifications();
Crashlytics.log("service call noti");
}
return START_STICKY;
}
this is my receiver that call my service:
#Override
public void onReceive(Context context, Intent intent) {
Log.e("receiver","work");
if (isNetworkConnected(context) == true) {
Log.e("receiver","wifi on");
Intent i = new Intent(context,ServiceNotifications.class);
i.putExtra("service_call",2);
context.startService(i);
} else {
Log.e("receiver","wifi off");
}
}
public static boolean isNetworkConnected(Context c) {
ConnectivityManager connectivityManager =
(ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
I also tried:
use start_stick service it won't work.
I'm trying use intent extra int instead of getaction but it didn't work either.
if you are not sure if intent is null or not but still you are making a call just move int getwhattodo = intent.getIntExtra("service_call",0); call inside your null check
int getwhattodo = intent.getIntExtra("service_call",0);
if (intent == null || intent.getAction() == null || getwhattodo == 0) {
Log.e("receiver","service faild");
Crashlytics.log("service faild to call");
if (getwhattodo == 0) {
stopSelf();
}
}
Related
I am developing a mobile app which keeps the screen ON when launched and all of you know that this kind of app drains the battery. So I wanted to keep the screen ON only when the device is plugged in. I found this code on stackoverflow (thanks to all of you).
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Context context = this;
Intent batteryStatus = context.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (isCharging) {
if (usbCharge) {
tv1.setText("USB plugged in");
} else {
if (acCharge) {
tv1.setText("AC plugged in");
}
}
} else {
tv1.setText("Connect your charger");
}
}
I put this code in oncreate. But the problem is that it shows status only once(when app is launched). So I put a timer task to repeat checking like this
t = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Context context = this;
Intent batteryStatus = context.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (isCharging) {
if (usbCharge) {
tv1.setText("USB plugged in");
} else {
if (acCharge) {
tv1.setText("AC plugged in");
}
}
But this doesn't work and gives the error
Type missmatch : Cannot convert from new Runnable(){} to Context
I am a newbie so please see if you could help me with some modification or even a new code. Thanks in advance.
Important note: I work on Sketchware which lets you only to put codes in MainActivity.xml or MainActivity.java other features like manifest.xml is not editable. Please keep this in mind while answering.
Use Broadcast Receiver to get Battery Status.
Like That:-
// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
int status=intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
if(status==BatteryManager.BATTERY_STATUS_CHARGING)
{
//Do anything if Charging
}
else
{
//Do anything if not Charging
}
}
}
Call it Like That:-
// Get the application context
Context mContext = getApplicationContext();
// Initialize a new IntentFilter instance
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
// Register the broadcast receiver
mContext.registerReceiver(mBroadcastReceiver,iFilter);
Hope this will help you!!!
I have used a switch in my android code.
If internet service is available then only allow toggle else show a toast message. How do I achieve this?
I am unable to do so using
switch.setOnCheckedChangeListener().
The check is working only if I press the switch button twice.
aSwitch.setEnabled(false);
works only after I click once
First create a boolean that carries a flag :
boolean checkInternetFlag = false;
Then create a method that check if internet is available like this for example:
public final boolean isInternetOn() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need to add this permission in your manifest :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then you can do what you want in a condition like this :
checkInternetFlag = isInternetOn();
if (!checkInternetFlag) {
Toast.makeText(getActivity(), "Internet not available", Toast.LENGTH_LONG).show();
}
Also you can disable your toggle switch like this :
aSwitch.setEnabled(false);
And to make switch not clickable use :
aSwitch.setClickable(false);
The following method will catch if there is a change occured to networkstate:
1)Add this code to onCreate():
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
2) Add OnDestroy() Method:
#Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();
unregisterReceiver(receiver);
}
3) Add the Following Code to your activity:
public class NetworkChangeReceiver extends BroadcastReceiver
{
#Override
public void onReceive(final Context context, final Intent intent)
{
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context)
{
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
if(!isConnected)
{
Log.v(LOG_TAG, "Now you are connected to Internet!");
aSwitch.setEnabled(true);
isConnected = true;
}
return true;
}
}
}
}
Toast.makeText(YourActivity.this, "Internet is not available", Toast.LENGTH_SHORT).show();
aSwitch.setEnabled(false);
isConnected = false;
return false;
}
}
4)Add this permission in your manifest file :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Hopefully this relates to your requirement.
I'm following a tutuorial to use google location services. So, I'm trying to get location using Google API service. But I got isGooglePlayServicesAvailable(this) is deprecated error. Can anyone help. Thanks
Below is my code for checking if Play services exist on device:
private boolean checkPlayServices(){
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS){
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}else {
Toast.makeText(getApplicationContext(),
"This device is not supported", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
Use isGooglePlayServicesAvailable instead
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
The correct way of checking if play services are available is:
private boolean isGooglePlayServicesAvailable(Context context) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context);
return resultCode == ConnectionResult.SUCCESS;
}
I'm trying to do this: connect to USB device and get the opened (or failed) connection. I did the logic according to examples and explanations that I have found, but I have problem with waiting for permission grant. First I tried a "good" way of using wait()+notifyAll(), than I tried straightforward loop with checks, but both times the waiting method (waitConnection()) was blocking for the timeout I gave it, and only after that the message was received. So I tried these 2 versions.
wait/notifyAll:
public UsbConnector startConnection(Context context) {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (syncObj) {
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
if (device.getVendorId() == vendorId && device.getProductId() == productId) {
connection = usbManager.openDevice(device);
connectedDevice = device;
}
}
}
syncObj.notyfyAll();
}
}
}
};
try {
usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device : usbManager.getDeviceList().values()) {
if (device.getVendorId() == this.vendorId && device.getProductId() == this.productId) {
context.registerReceiver(receiver, new IntentFilter(ACTION_USB_PERMISSION));
usbManager.requestPermission(device,
PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0));
break;
}
}
} catch (Exception e) {
}
return this;
}
public UsbDeviceConnection waitConnection(int timeout) {
try {
Thread.sleep(10, 0);
syncObj.wait(timeout);
} catch (InterruptedException e) {
}
return getConnection();
}
straightforward loop
public UsbConnector startConnection(Context context) {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
if (device.getVendorId() == vendorId && device.getProductId() == productId) {
connection = usbManager.openDevice(device);
connectedDevice = device;
}
}
}
permissionRequested = false;
}
}
}
};
try {
permissionRequested = false;
usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device : usbManager.getDeviceList().values()) {
if (device.getVendorId() == this.vendorId && device.getProductId() == this.productId) {
permissionRequested = true;
context.registerReceiver(receiver, new IntentFilter(ACTION_USB_PERMISSION));
usbManager.requestPermission(device,
PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0));
break;
}
}
} catch (Exception e) {
}
return this;
}
public UsbDeviceConnection waitConnection(int timeout) {
int waited = timeout;
while (permissionRequested && waited > 0) {
try {
Thread.sleep(10, 0);
} catch (InterruptedException e) {
}
waited -= 10;
}
return getConnection();
}
So in both cases, according to logs, the waitConnection() method (that is called by the consumer immediately after startConnection()) seems to block the execution (I gave it timeout 10 seconds, and it was blocked for 10 seconds), and only right after it's completed, the BroadcastReceiver gets the message. It appears that requestPermission() is not async (as I thought it is), but in this case, how is it possible that startConnection() exits immediately and before the message is received? And how can I wait for BroadcastReceiver to get the message? Say if I don't use the waitConnection() method, how my consumer should know the moment when it can start checking for connection availability?
"and only right after it's completed, the BroadcastReceiver gets the message"
The onReceived callback, by default, is called on the main thread. It sounds like you are calling waitConnection() on the main thread as well. Since waitConnection() blocks, the main thread cannot process any additional messages until waitConnection() returns. This means that onReceived will not be called until waitConnection() times out.
It is generally a bad idea to block the main thread. Read here
Instead, you could have onReceive launch a new activity which then does whatever it is you need to do once you get USB permission. That may or may not be the best solution for you, but regardless, the key here is to never block the main thread.
i am newbie in android.I have written this code its working fine and sending email as well but when i am pressing submit button it opens "Choose an email Client" on choosing "GMAIL" it opens gmail account and send it and showing toast message "Sending Message" and email send to destination address successfully and i am still on "Email Screen" Is there any method to check if email has reached to destination address successfully it returns me "true" else it returns me "false" so that on the basis of that boolean value i can set empty values on all editboxes or Refresh all Textboxes.
ImageView submitBtn = (ImageView)findViewById(R.id.askscreen_submit_btn);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// CALL GetText method to make post method call
//GetText();
SendEmailToAalim(email.getText().toString(),name.getText().toString(),address.getText().toString(),subject.getText().toString());
} catch (Exception ex) {
content.setText(" url exeption! ");
}
}
});
}
public void SendEmailToAalim(String email,String name,String address,String subject)
{
if(email == null || email.length()==0)
{
Toast.makeText(context,"Please Enter Email Id",Toast.LENGTH_LONG).show();
}
else if(email.length()>0 && email!= null && !checkEmailValidity(email))
{
Toast.makeText(context,"Please Enter Correct Email Id",Toast.LENGTH_LONG).show();
}
else if(subject == null || subject.length() == 0)
{
Toast.makeText(context,"Please Enter Value in Subject",Toast.LENGTH_LONG).show();
}
else if(name == null || name.length() ==0)
{
Toast.makeText(context,"Please Enter Value in Name Field",Toast.LENGTH_LONG).show();
}
else if(address == null || address.length() ==0)
{
Toast.makeText(context,"Please Enter Value in Address Field",Toast.LENGTH_LONG).show();
}
else if(email.length()!= 0 && checkEmailValidity(email) == true &&subject.length()!=0 && address.length()!=0 && name.length()!=0)
{
Intent emailSendIntent = new Intent(Intent.ACTION_SEND);
emailSendIntent.putExtra(Intent.EXTRA_EMAIL,new String[]{"abc32#yahoo.com"});
emailSendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailSendIntent.setType("message/rfc822");
//emailSendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(Intent.createChooser(emailSendIntent,"Choose an Email client :"));
}
}
public static boolean checkEmailValidity(CharSequence email)
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Here is the Screen Shot of Email Screen.Can someone please point me what should i need to do to alert user that email has been sent and refresh the page.
try to use these ::->
final Intent intent = new Intent(
android.content.Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"");
intent.putExtra(android.content.Intent.EXTRA_STREAM,
Uri.fromFile(new File("file name")));
final PackageManager pm = getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(
intent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm")
|| info.activityInfo.name.toLowerCase()
.contains("gmail"))
best = info;
if (best != null)
intent.setClassName(best.activityInfo.packageName,
best.activityInfo.name);
startActivity(intent);