I have created a broadcast receiver that should run when date changes, but it does not work when I change date of my phone. But when I change action to Change time zone, it works fine. I change phone's time zone and it runs perfectly. How should I test DATE_CHANGED action?
this is how did I add the Broadcast receiver in Manifest:
<receiver android:name=".service.CheckVersionBroadcast"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED"/>
</intent-filter>
</receiver>
This is my Broadcast Receiver:
public class CheckVersionBroadcast extends BroadcastReceiver {
CheckVersion checkVersion;
String latestVersion;
#Override
public void onReceive(Context context, Intent intent) {
checkVersion = new CheckVersion();
try {
latestVersion = checkVersion.execute().get();
Toast.makeText(ApplicationLoader.applicationContext,latestVersion,Toast.LENGTH_SHORT).show();
if(!latestVersion.equals(BuildConfig.VERSION_NAME)){
ApplicationLoader loader = new ApplicationLoader();
long when = System.currentTimeMillis();
loader.setUpNotification(ApplicationLoader.applicationContext,when);
}
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date strDate = sdf.parse(date1);
String sDate1 = date2;
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sDate1);
if (date1.after(strDate)) {}
}catch(exception e){
}
Related
I am doing an App that block some calls. I have a Broadcast Receiver to fix this. But when I kill my app (manually or by system), receiver doesn't work.
I have thought I need a service that execute a Broadcast Receiver, or block calls for itself. How can I do this?
Thank you for advantage.
EDIT
My receiver class:
public class IncomingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ITelephony telephonyService;
try {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Method m = tm.getClass().getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(tm);
if ((number != null)) {
telephonyService.endCall();
Toast.makeText(context, "Ending the call from: " + number, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(context, "Ring " + number, Toast.LENGTH_SHORT).show();
}
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Toast.makeText(context, "Answered " + number, Toast.LENGTH_SHORT).show();
}
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
Toast.makeText(context, "Idle " + number, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
My Receiver manifest:
<receiver
android:name=".ARQ.IncomingCallReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
I have to reboot the device on specific time.i am using below code for that
private void rebootAfterSomeTime() {
h = new Handler(Looper.getMainLooper());
r = new Runnable() {
public void run() {
//current time
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);
String currenttime = String.valueOf(hour) + " : " + String.valueOf(min) + " : " + String.valueOf(sec);
Log.d("Gajanand", "run: "+currenttime);
//comparing current time with 12:00pm
if (currenttime.equals("23 : 59 : 59")) {
//reboot the device
rebootDevice();
}
h.postDelayed(this, delayMillis);
}
};
h.post(r);
}
i am rebooting the device with two methods one by using powerManager and another by using SU..like below
private void systemAppsrebootOnly() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot(null);
}
public static void rebootDevice() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes("reboot \n");
} catch (Throwable t) {
t.printStackTrace();
}
}
Yes in both the cases device is rebooting properly.but the BroadcastReceiver is not triggering in both the case. but when i reboot device manually by long pressing power button and reboot that time BroadcastReceiver is triggering. here is my ShutdownReceiver
public class ShutdownReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*if(intent.getAction().equalsIgnoreCase("android.intent.action.BOOT_COMPLETED"))
{
Toast.makeText(context, "boot_completed", Toast.LENGTH_SHORT).show();
}
else*/
// Toast.makeText(context, ""+intent.getAction(), Toast.LENGTH_SHORT).show();
Log.e("kishan", "onReceive:mPowerReceiver powerofffffffffff");
ManvishPrefConstants.SHUTDOWN_TRIGGERED.write(true);
ManvishPrefConstants.SHUTDOWN_DATE_TIME.write(CommanUtils.formatDate(System.currentTimeMillis()));
}
}
Small part of my manifest file.i have added all necessary permissions.
<receiver android:name=".Activities.ShutdownReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN"/>
<action android:name="android.intent.action.ACTION_REBOOT"/>
<action android:name="android.intent.action.QUICKBOOT_POWEROFF"/>
</intent-filter>
</receiver>
any help ?
hey i have service its wallpaper service (not live wallpaper) so when I enter the app i have 5 radio buttons every button decide the time that the wallpaper changes and I have a button that triggers the service and i got response from my server even when i close the app but.... when i restart the device i get 1 response only and the wallpaper not changing lets say i was choised for every 4 second to change just when i reboot it stops and like i said i receive just one response from my server and stops even the wallpaper don't change with this response take a look at my code you will understand more (I used receiver and boot primission but ... );
MainActivity;
private final static int INTERVAL = 4000; //10 min
private final static int INTERVAL2 = 1000*60*30; // 30 min
private final static int INTERVAL3 = 1000 * 60 * 120; // 2 hours
private final static int INTERVAL4 = 1000 * 60 * 360; // 6 hours min
private final static int INTERVAL5 = 1000 * 60 * 1440; // 1 day
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rd1 = (RadioButton) findViewById(R.id.radioButton);
rd2 = (RadioButton) findViewById(R.id.radioButton2);
rd3 = (RadioButton) findViewById(R.id.radioButton3);
rd4 = (RadioButton) findViewById(R.id.radioButton4);
rd5 = (RadioButton) findViewById(R.id.radioButton5);
radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
mHandler = new Handler();
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this , WallService.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
if (rd1.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL, pintent);
} else if (rd2.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL2, pintent);
}else if (rd3.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL3, pintent);
}else if (rd4.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL4, pintent);
}else if (rd5.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL5, pintent);
}
}
});
}
service
String forecastJsonStr;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
final Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("yay.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("hey", buffer.toString());
}
if (buffer.length() == 0) {
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
}
});
thread1.start();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap result = Picasso.with(getBaseContext())
.load(hostName + hostWallpaperName + forecastJsonStr)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
receiver
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, WallService.class);
context.startService(pushIntent);
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.lol8">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".BootCompletedIntentReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".WallService"
android:enabled="true"
android:exported="true">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After device reboot alarms set in Alarm manager are cleared - docs
You need to initialize Alarm manager again in your on BOOT_COMPLETED receiver. You can use sharedPrefference to store the time you need to set your alarms
In onClick of the activity add
SharedPreference preference = PreferenceManager.getDefaultSharedPreference(this);
preference.edit.putInt("timeInterval",INTERVAL).apply;
Then in onReceive in the receiver:
SharedPreference preference =
PreferenceManager.getDefaultSharedPreference(this);
int interval = preference.getInt("timeInterval", 4000);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),interval, pintent);
Create a receiver and register like this in manifest, then onReceive() you need to start your service again
<receiver
android:enabled="true"
android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
I'm new to NFC with Android and I'm trying to make a kind of messaging app with NFC.
I have a first activity that sends the content of an EditText view to the other phone when beaming and displays the incoming message on a TextView on the other phone. This works fine.
I have another activity which is used to add a contact to the contacts register, it should work as the following:
A wants to add B as a contact,
A goes to the AddContactActivity, enters the name of the contact in the EditText view,
then B touches A's phone (on the same activity) and sends their identifier (public key, for further encryption).
My problem is that even though the code concerning the sending via NFC is basically the same between the two activities, when I beam on the second activity (AddContactActivity), the action of the intent sent is ACTION_MAIN instead of ACTION_NDEF_DISCOVERED, which has the effect of opening the first activity and thus not going through the right treatment.
Here is the code of the MainActivity:
public class MainActivity extends Activity {
private TextView mTextView;
private EditText mEdit;
NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
mTextView = (TextView)findViewById(R.id.retour);
mEdit = (EditText)findViewById(R.id.editText);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
#Override public NdefMessage createNdefMessage(NfcEvent event) {
String stringOut = mEdit.getText().toString();
byte[] bytesOut = stringOut.getBytes();
NdefRecord ndefRecordOut = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"text/plain".getBytes(),
new byte[] {},
bytesOut);
NdefMessage ndefMessageout = new NdefMessage(ndefRecordOut);
return ndefMessageout;
}
}, this);
checkAndProcessBeamIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
private void checkAndProcessBeamIntent(Intent intent) {
String action = intent.getAction();
if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)){
Parcelable[] parcelables =
intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage inNdefMessage = (NdefMessage)parcelables[0];
NdefRecord[] inNdefRecords = inNdefMessage.getRecords();
NdefRecord NdefRecord_0 = inNdefRecords[0];
String inMsg = new String(NdefRecord_0.getPayload());
mTextView.setText(inMsg);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(MainActivity.this,
intent.getAction().toString(),
Toast.LENGTH_LONG).show();
checkAndProcessBeamIntent(intent);
}
#Override
public void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public void generateKeys(){
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.YEAR, 1);
Date end = cal.getTime();
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
try {
kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext())
.setAlias("Keys")
.setStartDate(now)
.setEndDate(end)
.setSerialNumber(BigInteger.valueOf(1))
.setSubject(new X500Principal("CN=test1"))
.build());
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
kpg.generateKeyPair();
}
public void goToAddContact(View view) {
Intent intent = new Intent(this, AddContactActivity.class);
intent.setAction("NewActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}
Here is the code of the AddContactActivity:
public class AddContactActivity extends Activity{
NfcAdapter nfcAdapter;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
editText = (EditText)findViewById(R.id.editText);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
Intent intent = getIntent();
nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
#Override public NdefMessage createNdefMessage(NfcEvent event) {
String stringOut = getMyPublicKey();
byte[] bytesOut = stringOut.getBytes();
NdefRecord ndefRecordOut = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"text/plain".getBytes(),
new byte[] {},
bytesOut);
NdefMessage ndefMessageout = new NdefMessage(ndefRecordOut);
return ndefMessageout;
}
}, this);
checkAndProcessBeamIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Toast.makeText(AddContactActivity.this,
"onResume : "+intent.getAction().toString(),
Toast.LENGTH_LONG).show();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
public void addContactDataBase(String publicKey){
SQLiteHelper sqLiteHelper = new SQLiteHelper(this);
sqLiteHelper.addUser(new User(editText.getText().toString(), publicKey));
}
public void checkUserInDataBase(String publicKey){
SQLiteHelper sqLiteHelper = new SQLiteHelper(this);
User u = sqLiteHelper.getUser(publicKey);
Toast.makeText(AddContactActivity.this,
""+u.getName(),
Toast.LENGTH_LONG).show();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(AddContactActivity.this,
"OnNewIntent : "+intent.getAction().toString(),
Toast.LENGTH_LONG).show();
checkAndProcessBeamIntent(intent);
}
#Override
public void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
private void checkAndProcessBeamIntent(Intent intent) {
String action = intent.getAction();
if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)){
Toast.makeText(AddContactActivity.this,
"COUCOU",
Toast.LENGTH_LONG).show();
Parcelable[] parcelables =
intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage inNdefMessage = (NdefMessage)parcelables[0];
NdefRecord[] inNdefRecords = inNdefMessage.getRecords();
NdefRecord NdefRecord_0 = inNdefRecords[0];
String inMsg = new String(NdefRecord_0.getPayload());
addContactDataBase(inMsg);
checkUserInDataBase(inMsg);
}
}
public String getMyPublicKey(){
KeyStore ks = null;
RSAPublicKey publicKey = null;
try {
ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry("Keys", null);
publicKey = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
return publicKey.toString();
}
}
And here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bsauzet.testnfc" >
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddContactActivity"
android:label="#string/title_activity_add_contact"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
</manifest>
Check your appCompat libraries. Corruptness of appCompat libraries may cause wrong intent exceptions. Especially when you move your project from another PC or workspace (and/or IDE).
Getting an intent with ACTION_MAIN instead of ACTION_NDEF_DISCOVERED upon receiving an NFC event is a typical indication that an NDEF message containing an Android Application Record (AAR) was received and that the datatype of the first record of the NDEF message was not matched by any intent filter.
Your CreateNdefMessageCallback.createNdefMessage() method clearly does not add an AAR to the NDEF message. Consequently, the only reason why you would still receive an NDEF message containing an AAR would be that the createNdefMessage() raises an unhandled exception. In that case, the NFC stack will automatically generate an NDEF message containing a Play Store link and an AAR.
The most likely place that could cause createNdefmessage() to raise an unhandled exception is getMyPublicKey() (as that's the only part that differs between MainActivity and AddContactActivity).
So we can track the problem down to this part of your code:
ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry("Keys", null);
publicKey = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
This code either
raises an unhandled runtime exception (e.g. if ks, keyEntry, or keyEntry.getCertificate() is null, or if ks.getEntry("Keys", null) cannot be cast to a KeyStore.PrivateKeyEntry), or
raises any of the handled exceptions, which causes publicKey to be null which results in an unhandled NullPointerException upon trying to invoke the toString() (in return publicKey.toString();).
I have done the call recording in my application and am calling one Activity when the phone is in Ringing state.In that Activity just am showing the phone number and person name. For that I have written the code in my class which it extends BroadcastReceiver.
This scenario is working fine when I use the application. But If I close the application then am getting Unfortunately stopped
This is my AndroidManifest.xml.
<receiver android:name="com.domyhome.broadcastreceiver.IncomingCallInterceptor" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is my onRecive method. When am using my application If i get a call then the current activity is not going to the background. So I have written the code to finish the Activity.
#Override
public void onReceive(Context context, Intent intent) {
LoginActivity.login.finish();
MainActivity.main.finish();
telephonyRegister(context,intent);
}
This is the functionality. I'am calling the ProjectDailogActivity when the phone state is Ringing. I'am finishing the same Activity when the call is attended or ended.
public void telephonyRegister(final Context context, Intent intent)
{
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
ctx=context;
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
try
{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
if(ring==true&&callReceived==false)
{
Toast.makeText(context, "THIS IS MISSED CALL FROM"+phoneNumber, Toast.LENGTH_LONG).show();
String smsmessage = "Thanks for contacting us. We will get back you soon";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, "Dear Customer!"+" "+smsmessage, null, null);
Log.i("sms",smsmessage);
Toast.makeText(context, "SMS sent.",
Toast.LENGTH_LONG).show();
callReceived=false;
}
else if(callReceived==true)
{
try
{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
if(Conntact.isAvailable(phoneNumber))
{
try{
myAudioRecorder.release();
myAudioRecorder.stop();
myAudioRecorder = null;
}
catch(Exception e)
{
System.out.print("error");
}
Toast.makeText(context,"Recording Stopped", Toast.LENGTH_SHORT).show();
}
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
dir = Environment.getExternalStorageDirectory();
try {
file = File.createTempFile("sound", ".mp3", dir);
} catch (IOException e) {
e.printStackTrace();
return;
}
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(file.getAbsolutePath());
if(Conntact.isAvailable(phoneNumber))
{
callReceived = true;
ring=false;
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "recording started", Toast.LENGTH_SHORT).show();
}
else
{
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)){
phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
ring = true;
System.out.println("phonenum"+Conntact.isAvailable(phoneNumber));
if(!Conntact.isAvailable(phoneNumber))
{
Toast.makeText(ctx, phoneNumber+"not available", Toast.LENGTH_SHORT).show();
}
else if(Conntact.isAvailable(phoneNumber))
{
Intent intent11 = new Intent(ctx,ProjectDailogActivity.class);
intent11.putExtra("incoming_number",phoneNumber);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent11);
}
}
}
Conntact is a table where already some numbers has been stored. So when I get a call just am checking whether the calling number is available in the Conntact table.
If it is available then show the ProjectDailogActivity. If the number is available and the call is also picked means then do the recording. Everything is working fine . But it shows Unfortunately stopped when my app is not in use.
Consider unregistering for broadcast events while quitting from your app,Click here for a SO answer on same issue