I'm going by the following code example to dynamically build a preference activity.
http://www.linuxtopia.org/online_books/android/devguide/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromCode.html
The preference dialog shows, but I'm not able to see any changes after closing it.
Here's where I'm defining the activity in AndroidManifest.xml
<activity
android:name="PreferencesActivity" android:label="#string/preferences_name">
</activity>
Here's where I'm defining the receiver.
<receiver
android:name="FroyVisualReceiver"
android:label="#string/app_name"
android:exported="false">
<intent-filter>
<action android:name="com.starlon.froyvisuals.PREFS_UPDATE"/>
</intent-filter>
</receiver>
And here's the BroadcastReceiver. I never see the "WTF" in logcat. What am I doing wrong?
package com.starlon.froyvisuals;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
public class FroyVisualsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("WTFWTF", "WTFWTFWTFW");
String action = intent.getAction();
if(action.equals("com.starlon.froyvisuals.PREFS_UPDATE"))
{
((FroyVisuals)context).updatePrefs();
}
}
}
Oh here's onPause where I'm broadcasting the PREFS_UPDATE intent.I do see the logcat message. This method is part of my PreferenceActivity.
/** another activity comes over this activity */
#Override
public void onPause()
{
Log.i(TAG, "onPause ================================ ");
super.onPause();
Intent i = new Intent(this, FroyVisualsReceiver.class);
i.setAction("com.starlon.froyvisuals.PREFS_UPDATE");
sendBroadcast(i);
}
Edit: I think it may have to do with this line. 'this' points to my PreferenceActivity.
Intent i = new Intent(this, FroyVisualsReceiver.class);
Try a simple Intent:
Intent i = new Intent();
i.setAction("com.starlon.froyvisuals.PREFS_UPDATE");
sendBroadcast(i);
Related
I am trying to send an explicit broadcast to a receiver that's dynamically registered inside an activity but it doesn't seem to work. I've tried adding the action that the intent filter is expecting but that doesn't work either. Only when I use a public implicit intent it picks up the broadcast.
Could any one tell me why? The code is for Android 8.0+ and I have marked the line inside CustomReceiver.
In summary it should...
Service starts, dynamically registers a CustomReceiver to listen for a implicit broadcast.
CustomReceiver receives implicit broadcast, tries to send explicit broadcast to MainActivity.
MainActivity receiver catches the explicit broadcast and does something.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demos.democode">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<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=".CustomService" />
</application>
</manifest>
MainActivity.java
package com.demos.democode;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(CustomService.customActionActivity);
getApplicationContext().registerReceiver(activityReceiver, intentFilter);
Intent serviceIntent = new Intent(this,CustomService.class);
this.startForegroundService(serviceIntent);
Log.d("DEMO_APP", "create");
}
BroadcastReceiver activityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("DEMO_APP", "activity receiver");
}
};
}
CustomReceiver.java - Explicit broadcast from here doesn't work.
package com.demos.democode;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class CustomReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("DEMO_APP", "custom receiver");
// DOESN'T WORK! this explicit broadcast doesn't work even after setting an action in - why?
Intent i = new Intent(context, MainActivity.class);
i.setAction(CustomService.customActionActivity);
context.sendBroadcast(i);
// this implicit public broadcast works fine
i = new Intent(CustomService.customActionActivity);
context.sendBroadcast(i);
}
}
CustomService.java
package com.demos.democode;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class CustomService extends Service {
protected Context context = null;
public static String customAction = "EVENT_1";
public static String customActionActivity = "EVENT_2";
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
NotificationChannel serviceChannel = new NotificationChannel(
"DEMO_CHANNEL",
"Demo App",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
Notification notification = new NotificationCompat.Builder(context, "DEMO_CHANNEL")
.setSmallIcon(R.drawable.ic_launcher_foreground)
//.setContentText("Total screen time today: " + totalTimeDisplay )
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(1, notification);
startForeground(1, notification);
IntentFilter intentFilter = new IntentFilter(customAction);
CustomReceiver customReceiver = new CustomReceiver();
context.registerReceiver( customReceiver , intentFilter);
Log.d("DEMO_APP", "service created");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Intent i = new Intent(customAction);
Log.d("DEMO_APP", "service started");
sendBroadcast(i);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You are trying to launch an Activity using sendBroadcast()
In this code:
// DOESN'T WORK! this explicit broadcast doesn't work even after setting an action in - why?
Intent i = new Intent(context, MainActivity.class);
i.setAction(CustomService.customActionActivity);
context.sendBroadcast(i);
You are trying to launch an Activity, so the last line needs to be:
content.startActivity(i);
Sorry I am rather late to the party, but I think the error is in registration of receiver in the MainActivity. You have used
getApplicationContext().registerReceiver(activityReceiver, intentFilter);
Which is using application context to register receiver.
It should be replaced by:
registerReceiver(activityReceiver, intentFilter);
In which the receiver will be registered for that specific activity instance of Context.
I would like to make an app that starts up every time the device is unlocked.
I'm new to Android and although I've read dozens of answers and the documentation there are just too many moving parts that I'm having a hard time troubleshooting.
Here is what I have ...
Structure
app
- manifests
-- AndroidManifest.xml
- java
-- DisplayMessageActivity.java
-- MainActivity.java
- res
- UnlockReceiver.java
This is in in my AndroidManifest.xml
<receiver android:name="UnlockReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
This is my UnlockReceiver.java class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.xywebsolutions.myapplication.MainActivity;
public class UnlockReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
What am I doing wrong? Is it my Structure? Do I need to add permissions before adding the receiver?
You don't need any broadcast to start/stop video.
You can use onResume() of activity lifecycle to start video. onResume will be called when activity becomes visible to user.
onPause() of activity to pause the video. You can also save current play position and start from that position when activity started again using onSaveInstanceState() function
For your case you can try this
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
two changes and this issue was fixed:
1) The "UnlockReceiver" was moved into the java folder
app
- manifests
-- AndroidManifest.xml
- java
-- DisplayMessageActivity.java
-- MainActivity.java
-- UnlockReceiver.java
- res
And
2) The receiver in the manifest needed android:exported="true" ...
<receiver android:name="UnlockReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
I'm new to Android development, and I'm trying to create a simple "proof of concept application" which will run as a background service. I'm trying to use IntentService with a BroadcastReceiver to kick off the process (during boot time for now, at some point I might switch it to Screen on / user present).
I created a new project within Android Studio with no activity. Then I added the following Java files and made the following changes to the AndroidManifest.xml.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.circlesquires.netcountable.netcountable">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".SnapshotService" android:exported="true">
</service>
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
ServiceStarter.java
package com.circlesquires.netcountable.netcountable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by camha on 6/18/2016.
*/
public class ServiceStarter extends BroadcastReceiver{
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("output", "onReceive occured!");
if(intent.getAction().equals(ACTION)) {
Intent serviceIntent = new Intent(context, SnapshotService.class);
context.startService(serviceIntent);
}
}
}
SnapshotService.java
package com.circlesquires.netcountable.netcountable;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* Created by camha on 6/18/2016.
*/
public class SnapshotService extends IntentService {
public SnapshotService() {
super("SnapshotService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
while(true) {
Log.i("output", "I'm running!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I deploy the application to an emulator being sure to click the "debug" button. However I don't ever see ANY of the logs outputted in logcat.
I'm sure I'm doing something wrong--help me figure out what :D. Thanks!
android.intent.action.BOOT_COMPLETED is send, as its name suggest, after, but only after a device boot time. Are you restarting your device?
Instead of restarting device to test out your application, you can send system broadcasts directly through adb:
./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n <your.package.name>/.<YourReceiverClass>
You can find more info here.
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, SnapshotService.class);
context.startService(i);
}
compare direct with intent value instead of making string
and one thing more
On Android 3.1 and higher, the user must launch one of your activities before any manifest-registered BroadcastReceiver will work.
check this https://stackoverflow.com/a/17067671/3288890
I know this has been asked a million times before, but nothing is working for me. I have a service in a separate class that needs to be started when a button is pushed, after an application is launched from a LaunchIntent.
Long story short, here's my goal:
run commands>wait three seconds for commands to run>launch app>start service
The service is to monitor for the CONFIGURATION_CHANGED broadcast.
Manifest (the parts that matter):
</activity>
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.CONFIGURATION_CHANGED" >
</action>
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
</manifest>
MyService.java:
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import android.app.Service;
public class MyService extends Service {
String[] commandsdefault = {"/x"};
public void onCreate() {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
public void onDestroy() {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
public void onReceive(Context context, Intent intent) {
MainActivity ogres = new MainActivity();
ogres.RunAsRoot(commandsdefault);
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "x", Toast.LENGTH_SHORT);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And then I simply have the following line in my MainActivity.java to call the service to start:
startService(new Intent(getApplicationContext(), MyService.class));
I am more confused than a mosquito in a mannequin shop. LogCat is returning absolutely nothing helpful other than u=0 not found.
Do I have something incorrect here? I'm not even seeing toasts from the service starting.
Make sure your service is declared in Android manifest
try to Override the onStartCommand() method of your service. hope this helps
Try specifying the full name of your service as the android:name attribute (e.g. android:name="com.example.MyService")
Ok, solved my own question.
MyService was running the whole time! I just didn't see the toast notifications to alert me when it started. Now I have a monitor in my main Activity that posts a toast when the service is started/killed, rather than using MyService itself to post toasts.
Here's my code for DroidArmoryActivity
package com.maxgenero.droidarmory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class DroidArmoryActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.ibM4A1:
Intent intentM4A1 = new Intent("com.maxgenero.droidarmory.M4A1GUN");
startActivity(intentM4A1);
break;
}
}
}
It's not starting the java file (Activity) at all, no errors. Btw, the case is looking for an imageButton.
Here's my Manifest, at least the part you need:
<activity android:name=".M4a1"
android:label="#string/app_name"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="com.maxgenero.droidarmory.M4A1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And the file name for the java file is M4a1.java. If you need more info let me know, thanks.
I dont see where you define a listener on your Button or your View that will be clicked to launch the second Activity ??
yourView.setOnClickListener(this);
the second thing is that you should add declare your activity on your manifest file on the tag like this :
<activity android:name="your.package.name.NameOfYourAcitivity" />
the last thing is : try to instantiate the intent like this :
this.startActivity(new Intent(this, SecondActivity.class));
Regards,
Instead of...
case R.id.ibM4A1:
Intent intentM4A1 = new Intent("com.maxgenero.droidarmory.M4A1GUN");
startActivity(intentM4A1);
Try
Intent intentM4A1 = new Intent(this, ACTIVITY_NAME.class);
startActivity(intentM4A1);
Also dont forget to call your setOnclickListener().