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.
Related
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 am creating an application which perform specific task on receiving broadcast notification from specific application like whats app, viber etc .I have searched about this but did not get any solution. is there any possibility exist to do this action? if exist then please guide me how? :)
Simple Only follow this code and read the documentation from this link
Manifest File
<receiver android:name=".callbroadcastreceiver"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
In Java callbroadcastreceiver file
public class callbroadcastreceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra( TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Phone is ringing
}
else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//Call received
Toast.makeText( context,"call received",Toast.LENGTH_SHORT ).show();
context.startService( new Intent( context,BoundService.class ) );
}
else if (state.equals( TelephonyManager.EXTRA_STATE_IDLE)) {
//Call Dropped or rejected
context.stopService( new Intent( context,BoundService.class ) );
}
}
}
You can check on the status bar notification but you can't read them. If it can be it really danger situation for vulnerabilty.
But using Accessibility Service, you can only listen to all notification on the notification bar.
you can create a NotificationListenerService for this. Users may not be interested in giving your app the rights to monitor their notifications, though, which is why the user must manually enable this for your app.
but you can not read the content.
Try this to access your Notification form any Application
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.media.AudioManager;
import android.os.Parcelable;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import com.qna.vbage.Pref;
import static com.qna.vbage.FieldVerification.setRingerMode;
public class NotificationService extends AccessibilityService {
protected void onServiceConnected() {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
info.notificationTimeout = 3000;
setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent e) {
//Toast.makeText(this, "onAccessibilityEvent", Toast.LENGTH_SHORT).show();
Log.d("VBage", "FML");
if (e.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
// Toast.makeText(this, "onAccessibilityEvent 2", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved event");
Parcelable data = e.getParcelableData();
if (data instanceof Notification) {
// Toast.makeText(this, "onAccessibilityEvent 3", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved notification");
Notification notification = (Notification) data;
Log.d("VBage", "ticker: " + notification.tickerText);
Log.d("VBage", "icon: " + notification.icon);
Log.d("VBage", "notification: " + e.getText());
}
}
}
#Override
public void onInterrupt() {
setRingerMode(NotificationService_API18.this, AudioManager.RINGER_MODE_SILENT);
}
}
Set Permission in your Manifest
<uses-permission
android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions" />
set Service in Manifest to Call when App Start
<service android:name=".NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice" />
</service>
Create xml in you Values folder res/Values/xml/accessibilityservice.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeNotificationStateChanged"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100" />
You have to Enable Accessibility Manually for your App put below code in your Activity where you want to start Using this Service
if (!isAccessibilitySettingsOn(getApplicationContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
dialog.setNegativeButton("Go!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
});
showCusDialog(dialog, "Warning!", R.drawable.ic_warning, getString(R.string.accessiblityString));
}
to Start Service from Activity
startService(new Intent(mActivity, NotificationService_API18.class));
Today I started writing for android. I want a simple (I think) app that waits for notification with specified title and then does something. I tried this code for service
import android.app.NotificationManager;
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 android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
public class NotificationListener extends NotificationListenerService {
Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show();
String text = "";
String title = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Bundle extras = extras = sbn.getNotification().extras;
text = extras.getCharSequence("android.text").toString();
title = extras.getString("android.title");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show();
Log.i("Msg","Notification was removed");
}
}
Then added this to manifest:
<service
android:name=".NotificationListener"
android:enabled="true"
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>
finally started the service in MainActivity onCreate() startService(new Intent(context, NotificationListener.class));
onNotificationPosted does not work. It seems like service was started correctly, because toasts from onStartCommand and onCreate were shown. I tried on emulator and real device. I also allowed notification access in settings. Please help, I wasted 5 hours on that.
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'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);