Shake Device to Launch App - java

I am using this to work with Shake, and that works fine for me, but i wanna launch application when user shake their device,
see my code below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
transcript=(TextView)findViewById(R.id.transcript);
scroll=(ScrollView)findViewById(R.id.scroll);
shaker=new Shaker(this, 1.25d, 500, this);
}
#Override
public void onDestroy() {
super.onDestroy();
shaker.close();
}
public void shakingStarted() {
Log.d("ShakerDemo", "Shaking started!");
transcript.setText(transcript.getText().toString()+"Shaking started\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
public void shakingStopped() {
Log.d("ShakerDemo", "Shaking stopped!");
transcript.setText(transcript.getText().toString()+"Shaking stopped\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
So here is my question, how can i launch an application by shaking my device ?

You should write Android Service that will start your activity during shake. That is all. Services run in the background even if Activity is not visible
Service can be started eg. during device boot. This can be achieved using BroadCastReceiver.
Manifest:
<application ...>
<activity android:name=".ActivityThatShouldBeLaunchedAfterShake" />
<service android:name=".ShakeService" />
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
BootReceiver:
public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context, ShakeService.class);
context.startService(intent);
}
}
Service:
public class ShakeService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
... somewhere
if(shaked) {
Intent intent = new Intent(getApplicationContext(), ActivityThatShouldBeLaunchedAfterShake.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}

Write a separate app for Shake detection. On detection of shake, fire an intent with the package name of app, you want to launch:
Intent intent = new Intent (<PackageNameOfAppToBeLaunched>);
startActivity (intent);

Well What you need is Two different activity Where first One Detects your Shake which need to run all time in background and than call the new actual app you want to run on shake.
You can run your background activity you have to use class which will keep your activity run in background for long time(Continuously) you can use classes Like FutureTask or Executor (you can not use AsyncTask for this).
Whenever the thread passes command to Your Application open after Shake the Background process stops and command goes to app means you need to again immediately start background process after the actual app closed.

You need to write the code to launch the application to foreground from background while the shake started. This link will help you to do so.

Related

Fail to catch android.intent.action.MEDIA_BUTTON

My app that uses TextToSpeech to read some text is 90% finishes but has been stuck at this part for a few days. All I want is have the play/pause button of my bluetooth headset (Xiaomi's Mi Sports Bluetooth Earphones) to play/pause the TextToSpeech. I think it is the android.intent.action.MEDIA_BUTTON I need to catch, so I added these:
In AndroidManifest.xml:
<receiver android:name=".ButtonReceiver">
<intent-filter
android:priority="10000">
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
Then the class ButtonReceiver.java
public class ButtonReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "debug media button test", Toast.LENGTH_LONG).show();
// will finish the code once I catch this intent
}
}
The debug text does not show up. Though if I changed <action android:name="android.intent.action.MEDIA_BUTTON"/> to <action android:name="android.media.VOLUME_CHANGED_ACTION"/>, it does show the text when I press the volume up or down of the headset but this is not exactly what I want. I only want the app to respond to the play/pause button.
Then I read that I need to use registerMediaButtonEventReceiver, so I tried adding this in my MainActivity.java:
private AudioManager audioManager;
private ComponentName componentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
componentName = new ComponentName(this, ButtonReceiver.class);
audioManager.registerMediaButtonEventReceiver(componentName);
}
Still not working. Also, it says the registerMediaButtonEventReceiver is deprecated, so I am wondering if this is the reason that it does not work.
Further reading from the official document page, it tells this:
If you are running Android 5.0 (API level 21) or later, call
FLAG_HANDLES_MEDIA_BUTTONS
MediaBrowserCompat.ConnectionCallback.onConnected. This will
automatically call your media controller's dispatchMediaButtonEvent(),
which translates the key code to a media session callback.
I find this stupid, as I do not need this extra module to play media. All I need is the detection of the headset button press. Anyway, I tried to implement the MediaSession but gave up soon as it quickly ended up with too many codes that were useless for my app since my app is NOT an audio player app!
Any suggestion? What should I do?
I found the solution myself finally! Instead of making a separate BroadcastReceiver class, I added a public static class in my MainActivity.java:
public static class ButtonReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Toast.makeText(context, "debug media button test", Toast.LENGTH_SHORT).show();
...
}
}
Then added this line in onCreate:
((AudioManager)getSystemService(AUDIO_SERVICE))
.registerMediaButtonEventReceiver(new ComponentName(this, ButtonReceiver.class));
And finally in AndroidManifest.xml:
<receiver android:name=".MainActivity$ButtonReceiver"
android:enabled="true">
<intent-filter
android:priority="10000">
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
It works! The app can now catch the MEDIA_BUTTON intent with this setting!

Android 8.0 - Job Intent Service does not run application on bootup

Initially I had Android 7.0 and didn't have any issues using a BroadcastReceiver and service. However with changes to Android 8.0. I needed to switch to a JobIntentService so my application can run on bootup.
I have tried migrating my code to match the JobIntentService but nothing is happening on bootup.
I am unsure whether the reason is because of my service class or my BroadcastReceiver class.
AndroidManifest.xml
<service android:name=".backgroundService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
backgroundService.java
public class backgroundService extends JobIntentService {
public static final int JOB_ID = 0x01;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, backgroundService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, Home.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
}
startOnBoot.java
public class startOnBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i("In" , "getAction() - Boot");
backgroundService.enqueueWork(context, intent);
}
else
Log.i("No" , "Boot");
}
}
So I am trying to essentially start the Home.class on bootup.
I tried it and it could run normally. You could check three tips below.
1.Check whether you have declared RECEIVE_BOOT_COMPLETED permission or not.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2.Check whether you have declared the receiver with BOOT_COMPLETED action.
<receiver android:name=".startOnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3.Remove Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show(); in your service or toast it in main thread. Otherwise it gives you the error java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare().

Broadcast receiver not working when app is closed

So I have two different apps made, one sends a broadcast and another receives it and displays a toast. However, when I close the receiver app the broadcast is no longer received by the second app even though I defined the receiver in the manifest file.
The broadcast sender in the MainActivity of app1.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
Log.e("Broadcast","sent");
}
});
}
App 2 broadcast receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast has been recieved!", Toast.LENGTH_SHORT).show();
Log.e("SUCCESS", "IN RECIEVER");
//throw new UnsupportedOperationException("Not yet implemented");
}
App 2s Manifest:
<?xml version="1.0" encoding="utf-8"?>
<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">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.ali.rrr" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After registering my BroadcastReceiver (BR) statically in the manifest, applying the proper intent filters, using JobIntentService (and registering it in the manifest) to handle the work that was called from my BR, I was still getting inconsistent results.
Once all of what I listed above has been done you should be able to send an ADB command to activate your broadcast and process the work in your service even if the app is closed. This was working for me some of the time, but not all of the time.
This article describes limitation to BRs.
"As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu" (AKA a user executes Force Stop)
When I start the app by debugging it, then swipe it closed on my device, my ADB command never activates my BR. However, after my debugging session is over, when I open up the app on my device and swipe it closed, I can activate my BR through ADB commands.
This occurs because when you debug an application, then manually swipe it closed on the device, Android considers this a Force Stop hence why my BR cannot be activated until I re-open the app on the device without debugging.
Scoured the internet for hours, and wasn't able to find my solution, so I thought I'd post it here just in case some poor unfortunate soul is encountering the same weird functionality I was.
Happy coding :)
First of all you need to use the Service for this functionality to work.
In the Activity you can start and stop the service by using the below codes.
// to start a service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.startService(service);
// to Stop service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.stopService(service);
Then you can use the below service
public class MyBrodcastRecieverService extends Service
{
private static BroadcastReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
unregisterReceiver(br__ScreenOffReceiver);
m_ScreenOffReceiver = null;
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "ACTION_SCREEN_OFF");
// do something, e.g. send Intent to main app
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
I faced this issue recently. The BroadcastReceiver was working fine even if the app was removed from the background in the emulator and Samsung phones. But it failed to start my app in Chinese manufactured phones like Realme, Mi etc. While struggling to find a way to fix this I found that in the app details page there is battery optimisation settings where the Auto-launch feature was disabled. After I enabled it the app was working fine and BroadcastReceiver was able to start the app. I was unable ti find a way to enable this setting programmatically but I found this question which helped me direct the user to that setting page.
You can go through below solution;
Activity.java
Intent intent=new Intent(MainActivity.this,BroadcastService.class);
startService(intent);
BroadcastService.java
public class BroadcastService extends Service {
private static MusicIntentReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new MusicIntentReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.e("AAAAAAAAAA", "Headset is unplugged");
break;
case 1:
Log.e("AAAAAAAAA", "Headset is plugged");
break;
default:
Log.e("AAAAAAAAAAAA", "I have no idea what the headset state is");
}
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
Menifest
<service android:enabled="true" android:name=".BroadcastService" />
Try this way..
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
i.setComponent(
new ComponentName("PackageNameApp2","PackageNameApp2.MainActivity"));
sendBroadcast(i);

How to restart a service in android?

has anyone know how to restarting a service in android?? i have a service that called when device is booting.. and i have an option.java for saving my configuration..
if i editing a configuration in option.java, then i must restarting my service to takes the effect..
i only know how to start a service and after it running, i don't know how to restart it after a new configuration was made.. any idea??
startService(new Intent(this, ListenSMSservice.class));
Just stop the service and start it again
stopService(new Intent(this, ListenSMSservice.class));
startService(new Intent(this, ListenSMSservice.class));
In your element:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) In your element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class MyBroadcastreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
for more elaboration : this
So by observer-observable design pattern, I meant making use of FileObserver class provided by Android.
For example, here is a snippet from WallPaperManagerService.java from android's source code:
So, in your case, you would create a file observer (see sample code below) on the config file, and each time this config file changes, you will read all the values from your (already running) service.
Hope you got the essence of the idea.
/**
* Observes the wallpaper for changes and notifies all IWallpaperServiceCallbacks
* that the wallpaper has changed. The CREATE is triggered when there is no
* wallpaper set and is created for the first time. The CLOSE_WRITE is triggered
* everytime the wallpaper is changed.
*/
private final FileObserver mWallpaperObserver = new FileObserver(
WALLPAPER_DIR.getAbsolutePath(), CREATE | CLOSE_WRITE | DELETE | DELETE_SELF) {
#Override
public void onEvent(int event, String path) {
if (path == null) {
return;
}
synchronized (mLock) {
// changing the wallpaper means we'll need to back up the new one
long origId = Binder.clearCallingIdentity();
BackupManager bm = new BackupManager(mContext);
bm.dataChanged();
Binder.restoreCallingIdentity(origId);
File changedFile = new File(WALLPAPER_DIR, path);
if (WALLPAPER_FILE.equals(changedFile)) {
notifyCallbacksLocked();
}
}
}
};

Registering a headset button click with BroadcastReceiver in Android

I have a headset with single button and want to do a simple Toast when the button is pressed.
Right now I have the following code:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
And my main activity is the following:
public class mainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);
}
}
Nothing happens though when I push the button though.
I'm pretty sure something is wrong with my permissions/xml in the manifest. Here's the receiver XML so far:
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
....
and:
<uses-permission android:name="android.permission.BLUETOOTH" />
I notice in LogCat that when I press the button I get an error from "BluetoothIntentReceiver" saying "onReceive() Action : android.intent.action.MEDIA_BUTTON"
Just wanted to answer my own question in case others come across similar issues.
The code does work, just I wasn't seeing the Toast because I had another headset button controller app installed (and running in the background), so I guess it took priority over mine. However when I put
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //this line sets receiver priority
registerReceiver(r, filter);
It was able to work even with the other app installed. Also, you don't need both the above AND the XML, one or the other is fine as ways of registering the intent receiver.
Here's what I've got that's working in Android 4.2.2
In my manifest.xml I do this:
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
NB: this is instead of calling registerReceiver.
In my Main Activity's onCreate I need to call the AudioManager:
((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(
new ComponentName(
getPackageName(),
MediaButtonIntentReceiever.class.getName()));
I have found it will work without the AudioManager call, but not for long!
You shouldn't use setPriority
You register your broadcast receiver in the manifest
You then register your broadcast receiver using:
AudioManager#registerMediaButtonEventReceiver
The argument to registerMediaButtonEventReceiver is a ComponentName that points your broadcast receiver.
For a fully documented answer for Android >4.0 have a look here:
BroadcastReceiver for ACTION_MEDIA_BUTTON not working
If you don't want to use BroadcastReceiver, you can do this for Android >5.0 (API level 21 LOLLIPOP) using the MediaSession described here: https://stackoverflow.com/a/39413753/1386969

Categories