I know than this bug was commented in other blogs but I've tried to correct this and I did not succeed.
Only happend in android 8+, but in simulator of Android Studio works fine.
I have an app than activate a notification in some specific date, this notification remember some task for user. This works fine in android 7 or lower but in Android 8+ don't works. App works fine, but notification don't appear and in google Play is activated an ERROR.
My app never crash, only shows that error into Google Play console.
This is the bug in PlayStore Console:
java.lang.RuntimeException:
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3606)
at android.app.ActivityThread.access$1300 (ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1796)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:214)
at android.app.ActivityThread.main (ActivityThread.java:7045)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:964)
Caused by: java.lang.IllegalStateException:
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1666)
at android.app.ContextImpl.startService (ContextImpl.java:1611)
at android.content.ContextWrapper.startService (ContextWrapper.java:677)
at android.content.ContextWrapper.startService (ContextWrapper.java:677)
at com.example.tomas.memoru.R_Activate.onReceive (R_Activate.java:45)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3597)
And this is my source code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tomas.memoru" >
<permission android:name="com.example.tomas.memoru.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:name="com.example.tomas.memoru.R_Variables1"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<receiver
android:name=".R_Activate">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="com.example.tomas.memoru.R_Activate_generador" />
<service android:name="com.example.tomas.memoru.GcmIntentService" />
<receiver android:name="com.example.tomas.memoru.R_NotificationPublisher" />
<activity
android:name="com.example.tomas.memoru.R_Pantalla_Main"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize"
android:launchMode="singleInstance"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
R_Activate.java
package com.example.tomas.memoru;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.ArrayList;
public class R_Activate extends BroadcastReceiver {
Integer cont1 = 0;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
intent = new Intent(context,R_Activate_generador.class);
context.startService(intent);
Log.i("Autostart", "started");
}
}
}
R_Activate_generator.java
package com.example.tomas.memoru;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
public class R_Activate_generador extends Service {
ArrayList<String> task_cargar = new ArrayList<>();
Integer cont1=0;
static final int READ_BLOCK_SIZE = 100;
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public void onStart(Intent intent, int startid) {
cargadatosfile(); //this works fine, only charge information to check date and tasks
if(cont1>0){
scheduleNotification(getNotification("30 second delay"), 0);//this put notification
}
}
private void cargadatosfile() {
//this function works fine, only charge information to schedule the tasks
}
private void scheduleNotification(Notification notification, int delay) {
R_Variables1 comparteVariables = ((R_Variables1) getApplicationContext());
String s = "";
Integer temp_id = 0, masXdias=0;
String[] strValues_temp1;
Calendar today = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
cont1 = 0;
while (cont1 < task_cargar.size()) {
strValues_temp1 = task_cargar.get(cont1).split(";");
String[] strValues_time1 = strValues_temp1[11].split(" ");
String[] strValues_time2 = strValues_time1[1].split(":");
String[] strValues_date1 = strValues_time1[0].split("-");
Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
cal.set(Calendar.DATE, Integer.valueOf(strValues_date1[2]) + masXdias); //1-31
cal.set(Calendar.MONTH, Integer.valueOf(strValues_date1[1]) - 1); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR, Integer.valueOf(strValues_date1[0]));//year...
cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(strValues_time2[0])); //HOUR
cal.set(Calendar.MINUTE, Integer.valueOf(strValues_time2[1])); //MIN
cal.set(Calendar.SECOND, 0); //SEC
if (cal.after(today) ) {//fecha futura es la de File
Intent notificationIntent = new Intent(this, R_NotificationPublisher.class);
notificationIntent.putExtra(R_NotificationPublisher.NOTIFICATION_ID, Integer.valueOf(strValues_temp1[0]));// se reemplazo 1 por max_id
// notificationIntent.putExtra(R_NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, Integer.valueOf(strValues_temp1[0]), notificationIntent, PendingIntent.FLAG_ONE_SHOT);//FLAG_UPDATE_CURRENT // se reemplazo 0 por max_id
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT < 23){
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
else{
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(cal.getTimeInMillis(), pendingIntent), pendingIntent);
}
masXdias=0;
cont1++;
}
else{
masXdias=masXdias+1;
}
}
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(getNotificationIcon());
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.movando2_xx));
builder.setAutoCancel(true);
return builder.build();
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.movando2_xxbl : R.drawable.movando2_xx;
}
}
There are other java modules in my application, but the bug is in somewhere place of these code.
Thank you very much for your help, any hint and feedback is appreciated!.
Edwin
Related
Suppose I have a MainActivity.java, where if I press a button(id=get_button), I will go to the onReceive() of NotificationReceiver.java 2 minutes later :
But I am not going there. As for this and this and many other resources I googled, This seems to be the right way.
My MainActivity.java :
package com.example.insanes.chothavandar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.get_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MainActivity.this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 2);
cal.set(Calendar.SECOND, 0);
am.setRepeating(
AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
pendingIntent);
}
});
}
}
My NotificationReceiver.java :
package com.example.insanes.chothavandar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Not logging after 2 minutes
// Am I doing something wrong?
Log.d("DEBUG-EXISTENSE", "Reached in the broadcastreceiver");
}
}
I have registered the receiver in the manifest:
My menifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.insanes.chothavandar">
<uses-permission android:name="android.permission.INTERNET" />
<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>
<receiver android:name=".NotificationReceiver"/>
</application>
</manifest>
you want to write this code in your manifest file.
ex :
android:name="com.example.insanes.chothavandar.NotificationReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.example.insanes.chothavandar.SHOW_NOTIFICATION" />
</intent-filter>
</receiver>
If you will go to the onReceive() of NotificationReceiver.java 2 minutes later so, you will use a handler in your class.
ex:
private Handler mStatusHandler = new Handler();
private Runnable mStatusRunnable;
private void checkStatus() {
mStatusRunnable = new Runnable() {
#Override
public void run() {
// Hear right your on button click code.
checkStatus();
}
};
mStatusHandler.postDelayed(mStatusRunnable, 2000);
}
i don't know about the right way or not , but this can be done via Handler in pretty simple way,
int TIME=2000
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do stuff
}
}, TIME);
Alright, I have tried every solution on Stack and nothing works.My current method registers the "SmsListener" receiver from the MainActivity. All I'm trying to do is initialize the onReceive method. There are no errors; It simply isn't picking up a broadcast. What am I doing wrong? Pasting the applicable code here. Anything else that may be needed please just ask.
Update:
Here is a similar unresolved issue
Listen Android incoming SMS when Google Hangout or other app receives it
I am testing under Android 6.0.1. Target Sdk version is 22. Min Sdk is 19. It's worth noting that I just tested my original code on an LG Optimus GPro with Android 4.4.2 and it worked. It still isn't working on my Nexus with Android 6.0.1.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.biapps.makin_biscuits">
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<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" />
<action `android:name="android.service.notification.NotificationListenerService" />`
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ContactsList">
<intent-filter>
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
<receiver
android:name=".SmsListener"
android:priority="999"
android:enabled="true"
android:exported="true">
</receiver>
<receiver
android:name=".IncomingCallReceiver"
android:enabled="true"
android:exported="true">
</receiver>
</application>
Main Activity
package com.biapps.makin_biscuits;
import android.service.notification.NotificationListenerService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//set object labels and states here
private ImageButton icon;
private AudioManager am;
private ImageButton people;
private ImageButton ring;
private NotificationManager nm;
private NotificationListenerService nls;
IncomingCallReceiver broadCastReceiver = new IncomingCallReceiver();
SmsListener smsReceiver = new SmsListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
icon = (ImageButton) findViewById(R.id.icon);
icon.setOnClickListener(imgButtonHandler);
people = (ImageButton) findViewById(R.id.people);
//people.setOnClickListener(peopleButtonHandler);
ring = (ImageButton) findViewById(R.id.ring);
}
int buttonstate = 0;
public View.OnClickListener imgButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
if (buttonstate == 0) {
icon.setImageResource(R.drawable.buttonup);
buttonstate = 1;
am.setRingerMode(0);
registerReceiver(broadCastReceiver, new IntentFilter(
"android.intent.action.PHONE_STATE"));
registerReceiver(smsReceiver, new IntentFilter(
"android.intent.action.DATA_SMS_RECEIVED"));
registerReceiver(smsReceiver, new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED"));
registerReceiver(smsReceiver, new IntentFilter(
"android.provider.Telephony.DATA_SMS_RECEIVED"));
Toast.makeText(getApplicationContext(),"Diving!", `Toast.LENGTH_SHORT)`
.show();
} else {
icon.setImageResource(R.drawable.button);
buttonstate = 0;
am.setRingerMode(2);
unregisterReceiver(broadCastReceiver);
unregisterReceiver(smsReceiver);
Toast.makeText(getApplicationContext(),"Surfacing!", Toast.LENGTH_SHORT)
.show();
}
}
};}
SmsListener
package com.biapps.makin_biscuits;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import android.telephony.TelephonyManager;
public class SmsListener extends BroadcastReceiver {
private static final String TAG = "SmsListener";
public static final String SMS_BUNDLE = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "ON SMS RECEIVE BROADCAST", Toast.LENGTH_LONG).show();
Log.i(TAG, "SmsListener - onReceiveCalled");
}}
Try following way with highest reading priority value,
<receiver android:name=".SmsListener"
android:enabled="true"
android:exported="true"
android:permission="android.permission.READ_SMS">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
This will surely solve out your problem.
Update from below comment,
Since you are checking on Android version 6.0.1 just follow these steps,
Go to Settings,
Go to Apps
Select your Application
Choose Permissions Option
Enable SMS permission
After spending more than an hour I found that RECEIVE_SMS permission is required.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
Prioirty is not required to be set. This should work.
Found a solution.
First make another app your default SMS app.
Then: Google Hangout --> Settings (Disable merged conversations) --> SMS (Disable SMS)
You are registering broadcast your in your Activity, so it won't work if your app is in background. you can remove this from your Activity and you can register it in Manifest.
ex:
<receiver android:name=".SmsListener">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
Along with this add permission to recieve sms.
Try this, and it will work
Hello everybody this is my first post here and I must say I really like this site it helped me fix a lot of things. But now I have this problem when useing Alarm Manager in android from inside a Fragment.
Here is my code (snippet from stackoverflow), it used to work I tried to set the minutes to random and then it suddenly stopped working. When I removed it the error was still there..
Alarm.java :
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
RealityCheck.java
import com.actionbarsherlock.app.SherlockFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.CheckBox;
import android.widget.Toast;
public class RealityCheck extends SherlockFragment implements View.OnClickListener {
CheckBox EnabledBox;
Alarm alarm = new Alarm();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//Moet inflater gebruiken om findViewById in een Fragment te gebruiken en op het einde returnen
View rootView = inflater.inflate(R.layout.activity_reality_check, container, false);
EnabledBox = (CheckBox)rootView.findViewById(R.id.check_box_enabled);
EnabledBox.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
CheckBox EnabledBox = (CheckBox) v;
if(EnabledBox.isChecked())
{
//Moet this.getActivity gebruiken in Fragment
Toast.makeText(RealityCheck.this.getActivity(), "Reality check alarm activated", Toast.LENGTH_SHORT).show();
//Alarm starten (in fragment weer getActivity() ipv Context)
alarm.SetAlarm(getActivity());
}
else
{
Toast.makeText(RealityCheck.this.getActivity(), "Reality check alarm disabled", Toast.LENGTH_SHORT).show();
alarm.CancelAlarm(getActivity());
}
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dreamincubation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock" >
<receiver
android:process=":remote" android:name="Alarm"></receiver>
<activity
android:name="com.example.dreamincubation.IntroWindow"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.dreamincubation.MainActivity"
android:label="#string/title_activity_main_menu" >
</activity>
<activity
android:name="com.example.dreamincubation.RealityCheck"
android:label="#string/title_activity_reality_check" >
</activity>
<activity
android:name="com.example.dreamincubation.IncubationInfo"
android:label="#string/title_activity_incubation_info" >
</activity>
<activity
android:name="com.example.dreamincubation.Incubation"
android:label="#string/title_activity_incubation" >
</activity>
<activity
android:name="com.example.dreamincubation.AlarmService"
android:label="#string/title_activity_alarm_service" >
</activity>
<receiver android:name="Alarm" >
</receiver>
</application>
</manifest>
I've tried it without the wake-lock. Didn't work either.
If anybody can help me out it would be greatly appreciated..
You are telling to the AlarmManager to trigger immediatly by doing this:
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi);
And it should repeat the alarm every 10 minutes.
but if you want the first event to be in 10min and to repeat every 10 min you have to do this:
long tenMin = 1000 * 60 * 10;
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + tenMin, tenMin, pi);
I recommend to deal with the AlarmManager in a Service, a great tutorial explains it:
https://web.archive.org/web/20150626092455/http://blog.blundell-apps.com/notification-for-a-user-chosen-time [archive.org]
If you don't need an exact time alarm, you should definitly use the method:
setInexactRepeating
http://developer.android.com/reference/android/app/AlarmManager.html#setInexactRepeating(int, long, long, android.app.PendingIntent)
I order to preserve battery.
I am using Eclipse and I have installed the app in my Android phone.
Main Activity Code :
package com.example.usbdetection;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
UsbManager usbManager;
PendingIntent mPermissionIntent;
UsbDevice usbDevice;
Intent intent;
final String ACTION_USB_PERMISSION = "com.example.usbdetection.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
usbDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
usbManager.requestPermission(usbDevice, mPermissionIntent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbDevice != null) {
// call method to set up device communication
int deviceId = usbDevice.getDeviceId();
int productId = usbDevice.getProductId();
Log.i("device id", "****" + deviceId);
Log.i("product id", "****" + productId);
} else {
Log.i("device id", "No USB device");
}
} else {
Log.d("shiv", "permission denied for device ");
}
}
}
}
};
}
Manifest file :
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.usbdetection.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
</activity>
</application>
When I run my app and connect any USB it shows nothing. whats wrong?.
Any help would be appreciated :)
I have found the solution:
First i rooted my android device.
and then i added a file named android.hardware.usb.host.xml in etc/permissions Folder which include permission
<permissions>
<feature name="android.hardware.usb.host" />
</permissions>
And now it supports Host API.
I've found several tutorials about setting the alarm receiver to send a toast message in set intervals. and i've been following the code and broken down my own project into 3 classes.
the HelloDroidActivity.java is:
package com.example.helloandroid;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.example.helloandroid.alarms.MyAlarmReciever;
public class HelloDroidActivity extends Activity {
/** Called when the activity is first created. */
public static int RTC_WAKEUP;
public static long INTERVAL_FIFTEEN_MINUTES;
private AlarmManager alarmMgr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Krishneel");
setContentView(tv);
Toast.makeText(this, "Alarm went off", Toast.LENGTH_SHORT).show();
Log.d("OnCreate", "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd");
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 7000, pendingIntent);
}
}
also the MyAlarmReciever.java(i am already aware of the spelling mistake on the name):
package com.example.helloandroid.alarms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyAlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("onReceive", "ladskjflsakjdflskjdflskjdfslkjdflasdf");
Toast.makeText(context, "OnReceive alarm test", Toast.LENGTH_SHORT).show();
}
}
and the Android Manifest which looks like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.example.helloandroid.HelloDroidActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="com.example.helloandroid.alarms" />
</intent-filter>
</receiver>
</application>
</manifest>
I have read that in order to get the project to receive my alarmReceiver java class I need to edit the manifest with a new receiver. but I'm fairly new to XML and dont know which direction to take.
There is already a receiver that you have defined in your manifest file. But the name is not correct see the name needs to be the full class name i.e the package.RecieverName. And in your case the name of your receiver is MyAlarmReciever. So the receiver will be defined as follows
<receiver android:name=".alarms.MyAlarmReciever">
<intent-filter>
<action android:name="com.example.helloandroid.alarms" />
</intent-filter>
</receiver>
In your manifest, the receiver is listening to an action called com.example.helloandroid.alarms. But in your HelloDroidActivity.java there is not such action is added to the intent.
public class HelloDroidActivity extends Activity {
//....
#Override
public void onCreate(Bundle savedInstanceState) {
//....
Intent intent = new Intent(this, MyAlarmReciever.class);
intent.setAction("com.example.helloandroid.alarms");
//....
}
}