I don't know why my receiver does not receive any thing.
I want to send broadcast between two activities.
tv1 does not show "msg".
Here is the code
send:
Intent intent = new Intent(action);
intent.putExtra("msg", "a");
sendBroadcast(intent);
startActivity(new Intent(MainActivity.this,sec.class));
receiver:
IntentFilter intentFilter = new IntentFilter(MainActivity.action);
registerReceiver(receiver, intentFilter);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
tv1.setText(intent.getExtras().getString("msg"));
}
};
You can implement like this:
package com.example.broadcastrecieverdemo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private InternalReciever internalReciever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
internalReciever = new InternalReciever();
IntentFilter filter = new IntentFilter("kishan");
registerReceiver(internalReciever, filter);
findViewById(R.id.btnSendBroadcast).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("com.example.broadcastrecieverdemo.CUSTOM_INTENT");
sendBroadcast(intent);
}
});
findViewById(R.id.btnInternalSendBroadcast).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("kishan");
sendBroadcast(intent);
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(internalReciever);
super.onDestroy();
}
}
class InternalReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Inernal Broadcast recieved",
Toast.LENGTH_SHORT).show();
}
}
Reciever.java
package com.example.broadcastrecieverdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Reciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast recieved", Toast.LENGTH_SHORT)
.show();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<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/AppTheme" >
<activity
android:name="com.example.broadcastrecieverdemo.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>
<receiver android:name=".Reciever" >
<intent-filter>
<action android:name="com.example.broadcastrecieverdemo.CUSTOM_INTENT" >
</action>
</intent-filter>
</receiver>
</application>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Broad cast receiver"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btnSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="21dp"
android:gravity="center"
android:text="Send" />
<Button
android:id="#+id/btnInternalSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/btnSendBroadcast"
android:layout_marginTop="21dp"
android:gravity="center"
android:text="Send Internal" />
Related
I want to read notifications from other apps in android , but I am not able to do so. These are my implementations to achieve same.
This is my MainActivity.java
package com.example.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TableLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab = (TableLayout)findViewById(R.id.tab);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tab.addView(tr);
}
};
}
This is my NotificationService class
package com.example.demoapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.demoapp">
<dist:module dist:instant="true" />
<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>
<service android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
This is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab" />
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I have tested app in Android 5 and above, it is not getting any notification details. I gave permission to the app for reading permissions in android while testing on Android 6 and above versions.
Suggest me where I am getting wrong.
I have created a small demo for you its working fine in Android API-18 and above devices.
Even you can
Read all incoming SMS
Read all incoming calls
Battery Low and other notifications too
This is screenshot for display notification of other application Picture1 Picture2
NotificationService.java
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import java.io.ByteArrayOutputStream;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
Bitmap id = sbn.getNotification().largeIcon;
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
if(id != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
id.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
msgrcv.putExtra("icon",byteArray);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
try {
byte[] byteArray =intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if(byteArray !=null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
model.setName(title +" " +text);
model.setImage(bmp);
if(modelList !=null) {
modelList.add(model);
adapter.notifyDataSetChanged();
}else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demoapp">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.demoapp.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
Purpose: use AIDL to communicate two app (one is called service ,one is called client)
Condition: IDE: Android Studio ,In service ,I define a IPerson.aidl (in this file I define a interface called queryPerson )which AS will generate the IPerson.java in GENERATED dir . I also add IntentFilter(action ,category) AndroidMainfest.xml in main And I create a AIDLService to extends the IPerson.Stub and implement the interface queryPerson . After that I make another app called client to communicate with service But got NOPOINTER Exception
here are code in service:
IPerson.aidl:
// IPerson.aidl
package com.example.jason.aidldemo;
// Declare any non-default types here with import statements
interface IPerson {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String queryPerson(int num);
}
AIDLService.java:
package com.example.jason.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AIDLService extends Service {
private IBinder iBinder=new PersonQueryBinder();
private String [] names={"Apple","Banana","peach"};
private String query(int num)
{
if(num>0 && num<4)
{
return names[num-1];
}
return null;
}
public AIDLService() {
}
private final class PersonQueryBinder extends IPerson.Stub
{
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jason.aidldemo" >
<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.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".AIDLService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.AIDLService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>
In client:
activity-main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edit_num"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Query"
android:id="#+id/btn_query"
android:layout_below="#+id/edit_num"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tx_name"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn_query" />
</RelativeLayout>
MainActivity.java:
package com.example.jason.aidlclient;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.jason.aidldemo.IPerson;
public class MainActivity extends Activity implements View.OnClickListener {
private IPerson iPerson;
private Button btn_query;
private TextView tx_name;
private EditText edit_name;
private PersonConnection pconn=new PersonConnection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
//bind remoted service
Intent service=new Intent("android.intent.action.AIDLService");
service.setPackage("com.example.jason.aidldemo");
bindService(service,pconn,BIND_AUTO_CREATE);
}
private void bindView()
{
edit_name= (EditText) findViewById(R.id.edit_num);
btn_query= (Button) findViewById(R.id.btn_query);
tx_name= (TextView) findViewById(R.id.tx_name);
btn_query.setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_query:
String number=edit_name.getText().toString();
int num=Integer.valueOf(number);
try{
String temp=iPerson.queryPerson(num);
tx_name.setText(temp);
} catch (RemoteException e) {
e.printStackTrace();
}
edit_name.setText("");
break;
}
}
private final class PersonConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
iPerson= (IPerson.Stub) IPerson.Stub.asInterface(service);
}
#Override
public void onServiceDisconnected(ComponentName name) {
iPerson=null;
}
}
}
And I want Demo to run like this :
enter image description here
But got problem NOPOINTER
Hope someone teach ME!! THANKS!!
Your service is returning a null binder. You have to return the AIDL interface stub like this:
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IPerson.Stub(){
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
}
Hello there i'm newbie in Android development
I'm trying to make an app that changes the ringer profile when receive a specific sms, also i can change it by the buttons on the layout (the buttons are working good), but the sms way isn't working
i tried as shown below
MainActivity.java
package com.example.test;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button Vibrate , Ring , Silent , Mode;
private TextView Status,sms;
public static AudioManager myAudioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vibrate = (Button)findViewById(R.id.button2);
Ring = (Button)findViewById(R.id.button4);
Silent = (Button)findViewById(R.id.button3);
Mode = (Button)findViewById(R.id.button1);
Status = (TextView)findViewById(R.id.textView2);
sms = (TextView)findViewById(R.id.sms);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
}
public void vibrate(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
public void ring(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
public void silent(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
public void mode(View view){
int mod = myAudioManager.getRingerMode();
if(mod == AudioManager.RINGER_MODE_NORMAL){
Status.setText("Current Status: Ring");
}
else if(mod == AudioManager.RINGER_MODE_SILENT){
Status.setText("Current Status: Silent");
}
else if(mod == AudioManager.RINGER_MODE_VIBRATE){
Status.setText("Current Status: Vibrate");
}
else{
}
}
public static void messageProcessing(String message) {
if(message=="ring")
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
else if (message=="vibrate")
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
else if(message=="silent")
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
RecieveSMS.java
package com.example.test;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.os.Bundle;
public class RecieveSMS extends BroadcastReceiver
{
public static final String SMS_BUNDLE = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
MainActivity.messageProcessing(smsBody);
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="#string/audio"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="144dp"
android:layout_marginLeft="40dp"
android:layout_toLeftOf="#+id/button2"
android:onClick="silent"
android:text="#string/Silent" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/button1"
android:onClick="ring"
android:text="#string/Ring" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button2"
android:layout_alignLeft="#+id/button3"
android:layout_marginBottom="15dp"
android:onClick="mode"
android:text="#string/Mode" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="#string/Status"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button3"
android:layout_alignBottom="#+id/button3"
android:layout_alignRight="#+id/textView1"
android:onClick="vibrate"
android:text="#string/Vibrate" />
<TextView
android:id="#+id/sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView1"
android:layout_marginTop="23dp"
android:text="#string/Sms"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="audio">Set Audio Profiles</string>
<string name="Ring">Ring</string>
<string name="Vibrate">Vibrate</string>
<string name="Silent">Silent</string>
<string name="Mode">Current Mode</string>
<string name="Status">Current Status</string>
<string name="Sms">SMS</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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>
<receiver android:name=".RecieveSMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>
any help ??
also , well this app work in background or i should make a service to make that happen ?
I found out a way to solve my problem and that's how :
package com.example.test;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.media.AudioManager;
import android.os.Bundle;
public class RecieveSMS extends BroadcastReceiver
{
public static final String SMS_BUNDLE = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
//Edited from here
if (smsBody.contains("silent"))
{
Intent in = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
12345, in, PendingIntent.FLAG_CANCEL_CURRENT);
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
//To here
}
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
}
}
}
}
I have attached my code here for reference.
I need alarm to be executed after certain interval but its starting at the beginning and repeating. Can i get a solution for this.
AlarmManagerExample.java
package com.example.alarmmanagerexample;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
public class AlarmManagerExample extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager_example);
try {
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pendingIntent);
} catch (Exception e) {}
}
}
activity_alarm_manager_example.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlarmManagerExample" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
</RelativeLayout>
RingAlarm.java
package com.example.alarmmanagerexample;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class RingAlarm extends Activity {
MediaPlayer mp=null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
mp = MediaPlayer.create(getBaseContext(),R.raw.audio);
stopAlarm.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
mp.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(final Context context, Uri alert) {
Thread background = new Thread(new Runnable() {
public void run() {
try {
mp.start();
} catch (Throwable t) {
Log.i("Animation", "Thread exception "+t);
}
}
});
background.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
} //Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
}
Alarm.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Stop Alarm" android:id="#+id/stopAlarm"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmmanagerexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
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.alarmmanagerexample.AlarmManagerExample"
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=".RingAlarm"
android:label="#string/app_name" />
</application>
</manifest>
I want to start my app when a user press the power button. I m following This code
but its not showing any Log and toast.
here is my complete code.
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
// perform what you want here
}
}
menifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
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.powerbuttontest.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>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" >
</action>
<action android:name="android.intent.action.SCREEN_ON" >
</action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_SHUTDOWN" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java
package com.example.powerbuttontest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I think i m committing a mistake in my menifest file. please have a look on this. thanks.
First, unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! so You need to make a service which will keep on running like this
public static class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new Receiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// your code
} else {
// your code
}
}
}
and your receiver can be something
public class Receiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Here is my complete code. Hope this helps. I was basically making a look screen app. This will disable your default lock screen. and on power button press it will start a service and runs to look for power button press event.
Layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/toggleButton1"
android:layout_marginTop="72dp"
android:enabled="false"
android:text="Settings" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="72dp"
android:checked="true"
android:textOff="Disable"
android:textOn="Enable" />
</RelativeLayout>
MainActivity.java
package com.example.powerbuttontest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton btnToggleLock;
Button btnMisc;
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMisc = (Button) findViewById(R.id.button1);
btnToggleLock = (ToggleButton) findViewById(R.id.toggleButton1);
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
btnToggleLock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btnToggleLock.isChecked()) {
toast.cancel();
toast.setText("Unlocked");
toast.show();
Log.i("Unlocked", "If");
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.disableKeyguard();
MainActivity.this.startService(new Intent(
MainActivity.this, UpdateService.class));
} else {
toast.cancel();
toast.setText("Locked");
toast.show();
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.reenableKeyguard();
Log.i("Locked", "else");
MainActivity.this.stopService(new Intent(MainActivity.this,
UpdateService.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Log.i("onConfigurationChanged", "Called");
}
}
MyReciever.java
package com.example.powerbuttontest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.example.powerbuttontest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
// Toast.makeText(getApplicationContext(), "Sleep",
// Toast.LENGTH_LONG)
// .show();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Menifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<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>
<receiver android:name=".MyReceiver" />
<service android:name=".UpdateService" />
</application>
</manifest>
Here this one is the complete code, which will open your application as soon you presss power button. I am also doing the same project, where i want to open my Application directly after i press power button (turn on).
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_power_offon);
startService(new Intent(getApplicationContext(), LockService.class));
}//EOF Oncreate
}//EOF Activity
LockService.java
public class LockService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder
{
LockService getService() {
return LockService.this;
}
}//EOF SERVICE
ScreenReceiver.java
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
// do whatever you need to do here
wasScreenOn = false;
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ","shutdown now");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
// and do whatever you need to do here
wasScreenOn = true;
Log.e("Screen ","awaked now");
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
Log.e("LOB","userpresent");
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
}
}//EOF SCREENRECEIVER.JAVA
Now this is xml file, Please copy paste and just change the package name you are using
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.userpresent.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>
<service android:name="com.example.userpresent.LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>