I'm trying to make service that will do something each time phone call is ended. My problem is that service doesn't receive any broadcasts.
I've implemented it like that:
package com.kubasienki.spedycja;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
/**
* Created by kuba on 11/4/2015.
*/
public class FirstService extends Service {
private static String TAG = "kurwa";
final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.CALL_STATE_IDLE")){
Log.v("kurwa", "skonczono");
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
Log.v("kurwa", "???");
}
else {
Log.v("kurwa", "??!!!?");
}
}
};
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.d(TAG, "FirstService started");
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.TelephonyManager.CALL_STATE_IDLE");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(receiver, filter);
//this.stopSelf();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d(TAG, "FirstService destroyed");
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kubasienki.spedycja" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<activity android:name="com.kubasienki.spedycja.MainActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService" ></service>
</application>
</manifest>
And starting service :
startService(new Intent(this, FirstService.class));
Create a broadcast which listen for Call
class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {//do want you want
}
}
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<receiver android:name=".CallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
Handling Phone Call Requests the Right Way for Users
Perrmissions were in the wrong place.
Related
I've made a service with Android Studio but the service doesn't start when I click the button that I've setup to start the service. Here's my code, I start the service in the getInfo() method:
import ...
public class BasicInformation extends AppCompatActivity {
EditText name;
EditText height;
EditText weight;
private String nameStr;
private String heightStr;
private String weightStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_information);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
boolean firstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isfirstrun", true);
if (firstRun) {
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isfirstrun", false).commit();
} else {
Intent launchHome = new Intent(this, MainActivity.class);
startActivity(launchHome);
}
}
public void getInfo(View v) {
// This where I want to start the service
Intent service = new Intent(getApplicationContext(), StepCounterService.class);
startService(service);
name = (EditText) findViewById(R.id.input_name);
height = (EditText) findViewById(R.id.input_height);
weight = (EditText) findViewById(R.id.input_weight);
nameStr = name.getText().toString();
heightStr = height.getText().toString();
weightStr = weight.getText().toString();
Intent goToMain = new Intent(this, MainActivity.class);
startActivity(goToMain);
}
}
Here's my StepCounterService:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class StepCounterService extends Service {
public StepCounterService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Step Counting service started", Toast.LENGTH_LONG);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG);
}
}
And my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nina.stepcounter3">
<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"
android:configChanges="keyboardHidden|orientation"
android:label="#string/app_name"
android:screenOrientation="nosensor"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".BasicInformation"
android:label="#string/title_activity_basic_information"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".StepCounterService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
I am trying to detect if the WiFi is connected or not by listening to the "SUPPLICANT_CONNECTION_CHANGE_ACTION" as shown below in the code. But the problem is
when i run the App i receive no notificatio from the broadCast Receiver i am registered to!!
why that is happening and how to solve it?
code:
IntentFilter intentFilter2 = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityModule();
}
protected void ConnectivityModule() {
// TODO Auto-generated method stub
Log.d(TAG, "#interNetConnectivityModule: called");
registerReceiver(SupplicantReceiver, intentFilter2);
}
BroadcastReceiver SupplicantReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
}
}
};
Here is Example :
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// broadcast a custom intent.
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
My Broadcast Receiver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
This is how you should declare Broadcast Receiver in your Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<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="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="#+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/broadcast_intent"
android:onClick="broadcastIntent"/>
</LinearLayout>
Your receiver looks correctly registered (at runtime, not based on Manifest, but whatever, should be good anyway).
I'm guessing.. have you tried putting logs in onReceive method like
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "Reached this point, receiver is working");
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
Log.d(TAG, "Checking for an error in retrieving data!");
boolean myTest = intent.getBooleanExtra(EXTRA_SUPPLICANT_CONNECTED, false);
if (myTest) Log.d(TAG, "This way it worked!");
else Log.d(TAG, "This does not mean it didn't work at all! Might just be the correct value as a DISCONNECTED status");
} else Log.d(TAG, "Bizzarre error, action received was different from the one receiver was registered to! [ " + action + " ] ");
}
My guess is that you might be trying to retrieve the information in a wrong way, and with logs so strictly defined you can't see enough of what happens, but the receiver works fine
i have a string in my service, and i want to send it to fragment. But it seems onReceive() method on my BroadcastReceiver never called, and i just can't figured out why. Thanks for answers.
My Service Class
public class Servis extends Service {
static final String MAP = "MyService";
static final String USERID = "";
public static final String FILEPATH = "filepath";
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
System.out.println("starting service");
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
String id = intent.getStringExtra("UserID");
System.out.println(id);
Intent intent1 = new Intent(MAP);
intent1.putExtra(USERID, id);
sendBroadcast(intent1);
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(MAP, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(MAP, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(MAP, "onStart");
}
}
My Fragment Class
package com.example.mobilproje;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends FragmentActivity{
private GoogleMap googleHarita;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
handleResult(bundle);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_fragment);
registerReceiver(receiver, new IntentFilter(
Servis.MAP));
if (googleHarita == null) {
googleHarita = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.haritafragment))
.getMap();
if (googleHarita != null)
LatLng EvKoordinat = new LatLng(40.7994211,29.9517352);
googleHarita.addMarker(new MarkerOptions().position(EvKoordinat).title("Ev"));
googleHarita.moveCamera(CameraUpdateFactory.newLatLngZoom(EvKoordinat, 13));
}
}
}
#Override
public void onResume() {
registerReceiver(receiver, new IntentFilter(
Servis.MAP));
}
private void handleResult(Bundle bundle) {
if (bundle != null) {
String string = bundle.getString(Servis.USERID);
System.out.println("string");
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mobilproje"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/nfc"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:theme="#style/mytheme"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity
android:name=".MapFragment"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCgPPczPpQA_00_v-nTux_WuGuaO9egUpc" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:enabled="true" android:name=".Servis" android:process=":localservice"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</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>
hi friends i am unable to send Broadcast from one activity to other activity pls see my code below and help:
public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";
/* }
});
}
public void sendBroadcast(){
Intent broadcast = new Intent("com.unitedcoders.android.broadcasttest.SHOWTOAST");
this.sendBroadcast(broadcast);
//startActivity(broadcast);
}
}
Receiving side code:
public class ToastDisplay extends Activity {
private BroadcastReceiver mReceiver;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("!!!!!!!InchooTutorial#######$$$$","%%%%%%% msg_for_me");
ent
// String msg_for_me = intent.getStringExtra("some_msg");
//log our message value
Log.i("!!!!!!!InchooTutorial#######$$$$","%%%%%%% msg_for_me");
}
};
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
}
Manifest.xml is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unitedcoders.android.broadcasttest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SendBroadcast"
android:label="#string/app_name">
<intent-filter>
nitedcoders.android.broadcasttest.SHOWTOAST" />
</application> </manifest>
Since the other activity is not running when u send broadcast u wont receive it.
If u want to receive broadcasts even when the activity is not running . Declare it in xml .
Here is the code for you. I hope this is what you want.
package com.pdd.Receiver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ReceiverActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent("com.pdd.receiver.myaction");
sendBroadcast(i);
}
}
Receiver Class
package com.pdd.Receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
//Intent i=new Intent(MyReceiver.class,Second.class);
Intent i=new Intent(arg0,Second.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(i);
}
}
Second Activity to display Toast
package com.pdd.Receiver;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "This is second activity", 5000).show();
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pdd.Receiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="com.pdd.Receiver.MyReceiver">
<intent-filter>
<action android:name="com.pdd.receiver.myaction"></action>
</intent-filter>
</receiver>
<activity
android:name=".ReceiverActivity"
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=".Second"></activity>
</application>
</manifest>
If your SendBroadcast activity is created the broadcast will be send.
Then you start the second activity called ToastDisplay and in the onResume you register the BroadcastReceiver. But this is to late, the broadcast was already send, it will not stay in the system!
Try sending a stickybroadcast like:
sendStickyBroadcast(Intent)
Or declare the broadcastreceiver in the manifest but then you need to create a seperate class that extends the BroadcastReceiver class, this cannot be inherreted.