switch off broadcast receiver - java

I want to send an sms to someone's phone before the phone get switched off. here is the broadcast receiver but it does not work.
public class SwitchOff extends BroadcastReceiver {
SharedPreferences sharedPreferences;
public SwitchOff() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
sendSMS(sharedPreferences.getString("number", "error"), "Child Name:" +
sharedPreferences.getString("childName", "Service child Name not found") +
"\nStatus: Mobile is being turned off");
Toast.makeText(context, "i am going to turned off",
Toast.LENGTH_SHORT).show();
}
private void sendSMS(String phoneNumber, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null,
null);
}
}
and here is my manifest
<receiver
android:name=".SwitchOff"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.QUICKBOOT_POWEROFF"
/>
</intent-filter>
</receiver>

Related

How can I display the incoming number as a Toast?

I have to make a simple App for school.
It has to show a toast when a call is received.
The phone call receiver doesn't display anything.
I have this in my manifest, so permissions shouldn't be the issue
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".ReceptorLlamadas"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
The code for my broadcastReceiver
public class ReceptorLlamadas extends BroadcastReceiver {
Context context;
#Override
public void onReceive(Context c, Intent intent) {
try {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
LlamadaListener listener = new LlamadaListener();
manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
Log.e("PhoneCallError", "onReceive: ", e);
}
}
private class LlamadaListener extends PhoneStateListener {
public void onCallStateChanged(int state, String phoneNumber) {
if (state == 1) {
String mensaje = "Llamada entrante del número: " + phoneNumber;
int duracion = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, mensaje, duracion);
toast.show();
}
}
}
}
Sorry if I messed up the formatting
Edit: forgot to include some code
You need to declare Broadcast Receiver in Android Manifest as well just like this in Application tag:
<receiver
android:name=".ReceptorLlamadas"
android:enabled="true" />

Android Broadcast Receiver not working (with two receiver)

I have two BroadcastReceiver and only one is working now.
Manifest
<receiver
android:name="com.example.basicplayerapp.core.AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
<!-- WebSocket -->
<receiver
android:name="com.example.basicplayerapp.core.NetworkReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service android:name="com.example.basicplayerapp.core.WebSocketServices"></service>
When I have only the AudioJackReceiver it works prefect. Now that I added NetworkReceiver the AudioJackReceiver stopped work. Any advice please. thanks.
onCreate of the Video Activity
if (HEADSET_ONLY) { myAudioJackReceiver = new AudioJackReceiver(); }
AudioJackReceiver
public class AudioJackReceiver extends BroadcastReceiver {
public static final String TAG = AudioJackReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
audio.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast.makeText(context, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_LONG).show();
makeLog("i", "Headset is unplugged");
break;
case 1:
audio.setStreamMute(AudioManager.STREAM_MUSIC, false);
makeLog("i", "Headset is plugged");
break;
default:
makeLog("i", "I have no idea what the headset state is");
Toast.makeText(context, "ERROR => I have no idea what the headset state is", Toast.LENGTH_LONG).show();
}
}
}//end onReceive
NetworkReceiver
public class NetworkReceiver extends BroadcastReceiver {
public static final String TAG = NetworkReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.i(TAG, "connected");
Intent startServiceIntent = new Intent(context, WebSocketServices.class);
context.startService(startServiceIntent);
}
else if(networkInfo != null){
NetworkInfo.DetailedState state = networkInfo.getDetailedState();
Log.i(TAG, state.name());
}
else {
Log.i(TAG, "lost connection");
}
}//end onReceive
};//end NetworkReceiver

Android - Try to send fake sms to myself without mobile network usage

I'm trying to send message to my phone with this app, without using network usage, but my code doesn't work. I followed some tutorial, check android dev and I haven't found anything (in my logcat I don't have error). Could you help me to find out my problem.
My information about compilation, compiler and phone:
Android Studio 1.0.1
API 19 Android 4.4.4 (kitkat)
Build 19
Android phone version 4.4.4
Manifest:
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
Function of my main activity:
Context context;
String sender;
String body;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get current context
context = this;
//App started
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
CheckApp();
}
private void CheckApp() {
sender = "1234";
body = "Android sms body";
//Get my package name
final String myPackageName = getPackageName();
//Check if my app is the default sms app
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
//Get default sms app
String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context);
//Change the default sms app to my app
Intent intent = new Intent( Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
startActivity(intent);
//Write the sms
WriteSms(body, sender);
//Change my sms app to the last default sms app
Intent intent2 = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent2.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
startActivity(intent2);
}
else{
//Write the sms
WriteSms(body, sender);
}
}
//Write the sms
private void WriteSms(String message, String phoneNumber) {
//Put content values
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, phoneNumber);
values.put(Telephony.Sms.DATE, System.currentTimeMillis());
values.put(Telephony.Sms.BODY, message);
//Insert the message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
context.getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
}
else {
context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
}
Well, this is what i wanna do but with my own app and not with the app Fake Text Message that downloaded to the play store.
Make the fake message and what should i see on my default sms app:
With the help from Mike M. I finally finished my program. So, this is the code that you must add to your app to be able to send sms without using network:
Manifest:
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- BroadcastReceiver that listens for incoming SMS messages -->
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<!-- BroadcastReceiver that listens for incoming MMS messages -->
<receiver android:name=".MmsReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<!-- My activity -->
<activity
android:name=".MainActivity"
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 that allows the user to send new SMS/MMS messages -->
<activity android:name=".ComposeSmsActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</activity>
<!-- Service that delivers messages from the phone "quick response" -->
<service android:name=".HeadlessSmsSendService"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
</application>
Main Activity:
Context context;
Button button;
String sender,body,defaultSmsApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get current context
context = this;
//Set composant
button = (Button) findViewById(R.id.button);
//Get default sms app
defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context);
//Set the number and the body for the sms
sender = "0042";
body = "Android fake message";
//Button to write to the default sms app
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get the package name and check if my app is not the default sms app
final String myPackageName = getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(context).equals(myPackageName)) {
//Change the default sms app to my app
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
startActivityForResult(intent, 1);
}
}
});
}
//Write to the default sms app
private void WriteSms(String message, String phoneNumber) {
//Put content values
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, phoneNumber);
values.put(Telephony.Sms.DATE, System.currentTimeMillis());
values.put(Telephony.Sms.BODY, message);
//Insert the message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
context.getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
}
else {
context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
//Change my sms app to the last default sms
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
context.startActivity(intent);
}
//Get result from default sms dialog pops up
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
final String myPackageName = getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(context).equals(myPackageName)) {
//Write to the default sms app
WriteSms(body, sender);
}
}
}
}
As a result of adding things in your manifest you must add 4 classes: SmsReceiver, MmsReceiver, ComposeSmsActivity and HeadlessSmsSendService. You can let them empty as shown below.
SmsReceiver:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
MmsReceiver:
public class MmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
ComposeSmsActivity:
public class ComposeSmsActivity extends ActionBarActivity {
}
HeadlessSmsSendService:
public class HeadlessSmsSendService extends IntentService {
public HeadlessSmsSendService() {
super(HeadlessSmsSendService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
If you need more help to understand this program have a look there:
Youtube - DevBytes: Android 4.4 SMS APIs
Android developers - Getting Your SMS Apps Ready for KitKat
Possiblemobile - KitKat SMS and MMS supports

Android - Start App Upon Phone Call

Is there any way to develop an app that starts up when a user receives a phone call? I can't really go into details about the idea but was wondering if there was some call that would allow that to happen.
You can use a Broadcast Receiver for thatlike this
public class PhoneStatReceiver extends BroadcastReceiver{
private static final String TAG = "PhoneStatReceiver";
private static boolean incomingFlag = false;
private static String incoming_number = null;
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
incomingFlag = false;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG, "call OUT:"+phoneNumber);
}else{
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
incomingFlag = true;//标识当前是来电
incoming_number = intent.getStringExtra("incoming_number");
Log.i(TAG, "RINGING :"+ incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(incomingFlag){
Log.i(TAG, "incoming ACCEPT :"+ incoming_number);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if(incomingFlag){
Log.i(TAG, "incoming IDLE");
}
break;
}
}
}
}
Register this receiver in AndroidManifest like this
<receiver android:name=".filter.PhoneStatReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>
Yes We can start an diffrent app when User receives a phone call.Example :- Truecaller,Mobile no. Tracker apps.
You can use Services for this.
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
final Context cont = context;
final Intent in = intent;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(cont, MainActivity.class);
i.putExtras(in);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
cont.startActivity(i);
}
}, 1000);
}
}
}
You must implement this handler with postDelayed so that your activity screen can be on top of native call screen. If you dont want this to happen then you must remove this handler.
Add these to your manifest--
<receiver
android:name=".CallReceiver"
android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
You have to use another extra_state for onreceiving call. This is for ringing state.

Intent not received by Broadcast Receiver

I'm trying to show a message when a user places a call using the standard android dialer.
I have the following code in my Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTestButtonListener();
Log.i(LOG_TAG, "Activity started...");
}
private void setTestButtonListener()
{
Button testButton = (Button)this.findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.i(LOG_TAG, "Clicked on test...");
Toast.makeText(getApplicationContext(), (CharSequence)"You clicked on the test button" ,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+150));
MainActivity.this.sendOrderedBroadcast(intent, null);
MainActivity.this.startActivity(intent);
Log.i(LOG_TAG, "intent broadcasted... I think... ");
}
});
}
Then in the BroadcastReceiver (well a class that derives from it):
public class OnMakingCallReceiver extends BroadcastReceiver
{
private static final String LOG_TAG = OnMakingCallReceiver.class.getSimpleName() + "_LOG";
#Override
public void onReceive(Context context,Intent intent)
{
Log.i(LOG_TAG, " got here!");
}
}
And then in the AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE" />
<receiver android:name=".OnMakingCallReceiver" android:priority="999">
<intent-filter>
<action android:name="android.intent.action.CALL"/>
</intent-filter>
</receiver>
I click the test button and I see this output.
Clicked on test...
intent broadcasted... I think...
And thats all. I expected to see "got here!".
Any ideas why I don't?
Did you define the receiver in your AndroidManifest.xml?
Also, ACTION_CALL_BUTTON is sent when you click on something that goes directly to the dialer. Are you sure you're doing that.
I used this in AndroidManifest.xml and it works. I think the key thing is the intent NEW_OUTGOING_CALL in the intent-filter.
<receiver android:name=".OnMakingCallReceiver" android:exported="true" android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.ACTION_CALL" />
</intent-filter>
</receiver>
Probably ACTION_CALL could be removed. Also this may need to be added to the manifest:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

Categories

Resources