I am developing an android app which should be able to identify when someone press the hardware volume up button of the phone , and give a notification saying "volume up button has pressed".
This is my BroadcastReceiver class.
package com.example.volumebut;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.widget.Toast;
public class HardwareButtonReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
KeyEvent e = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if(e.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
Toast.makeText(context, "volume up button pressed." ,Toast.LENGTH_LONG).show();
}
}
}
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volumebut"
android:versionCode="1"
android:versionName="1.0" >
<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.volumebut.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=".HardwareButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
</manifest>
Since I am new to android development I have no idea how to implement MainActivity.java file.
This is the MainActivity.java file I have wrote so far. But it gives an error saying "The method registerMediaButtonEventReceiver(HardwareButtonReceiver) is undefined for the type MainActivity"
package com.example.volumebut;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
HardwareButtonReceiver receiver = new HardwareButtonReceiver();
registerMediaButtonEventReceiver(receiver);
}
}
If you guys can help me to solve my problem I appreciate It much.
http://developer.android.com/reference/android/view/KeyEvent.html
go through above link you will get different key events
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//
}
else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
}
return super.onKeyDown(keyCode, event);
}
You must add method registerMediaButtonEventReceiver to your activity class.
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_of_your_activity);
HardwareButtonReceiver receiver = new HardwareButtonReceiver();
registerMediaButtonEventReceiver(receiver);
}
private void registerMediaButtonEventReceiver(HardwareButtonReceiver receiver) {
}
}
And then implement it of course.
Related
I'm unable to make WorkManager survive reboot. I want my tasks to be executed automatically even after reboot.
My Device is Realme X2 with Android 10.
WorkManager is working fine. But the moment i reboot my phone and wait for 15 mins for my tasks to be executed but it simply never executes.
WorkManagerReceiver.java
package com.example.surviverebootwm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import java.util.concurrent.TimeUnit;
public class WorkManagerReceiver extends BroadcastReceiver {
WorkManager mWorkManager;
#Override
public void onReceive(Context context, Intent intent) {
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
mWorkManager = WorkManager.getInstance(context);
mWorkManager.enqueue(myWork);
}
}
TestWorker.java
package com.example.surviverebootwm;
import android.content.Context;
import android.media.MediaPlayer;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
public class TestWorker extends Worker {
public TestWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_ALARM_ALERT_URI);
mediaPlayer.setLooping(true);
mediaPlayer.start();
return Result.success();
}
}
MainActivity.java
package com.example.surviverebootwm;
import androidx.appcompat.app.AppCompatActivity;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance(MainActivity.this)
.enqueueUniquePeriodicWork("testworker", ExistingPeriodicWorkPolicy.KEEP, myWork);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.surviverebootwm">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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>
<receiver android:name=".WorkManagerReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
</manifest>
Im trying to make an app that getting all notifications and do the task. But my problem is NotifycationListener service starting automaticly even i didnt call the start service. Its starting as soon as I allow the app notification access on my phone. So service starting somehow and I cant stop it. Im already try simple services they working correctly. But this one with the NotificationListener is really painful. I just want to start and stop this service by my command.
Service start by itself when I allow this (screenshot)
MainActivity
package com.example.alperen.nservice2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startB,stopB;
Intent intent;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB=(Button)findViewById(R.id.button);
stopB=(Button)findViewById(R.id.button2);
startB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
});
stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopService(intent);
}
});
}
}
MyService Class
package com.example.alperen.nservice2;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
public class MyService extends NotificationListenerService{
#Override
public void onCreate() {
super.onCreate();
System.out.println("********* SERVICE STARTED ***********");
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
System.out.println("***** notification *****");
String pack,title,text;
Bundle extras;
try {
pack = sbn.getPackageName();
extras = sbn.getNotification().extras;
title = extras.getString("android.title").toString();
text = extras.getCharSequence("android.text").toString();
}catch (Exception e)
{
System.out.println("**** HATA NOTIFYSERVICE CLASS ****");
pack="empty1";
title="empty1";
text="empty1";
System.out.println("**** "+pack+" ****");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
Toast.makeText(this,"title: "+title+" text: "+text,Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
System.out.println("***** destroyed *****");
super.onDestroy();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alperen.nservice2">
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
tools:ignore="ProtectedPermissions" />
<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=".MyService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
></service>
</application>
And the tricky part is in the Manifest. When I delete intent-filter part and run the app. It doesn't want to notification access anymore and it doesn't start by itself. I can start and stop the service from the MainActivity with buttons. But this time the app not getting the notification.
// just delete this lines
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
This is an intended behavior.
When you grant notification access permission (or restart the phone) then SYSTEM is binding to your NotificationListenerService in order to send notification data.
If you override your services onBind method and log it, you will see it's being called.
I have an application, which you should be able to recreate entirely and very easily with the code I'll post in this question. Here's the Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcasttest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.broadcasttest.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="com.example.broadcasttest.TestReceiver"
android:label="#string/app_name"
android:enabled="true" >
</receiver>
<intentservice
android:name="com.example.broadcasttest.MonitorService"
android:enabled="true" >
<intent-filter>
<action android:name="com.example.broadcasttest.MonitorService" />
</intent-filter>
</intentservice>
</application>
</manifest>
As you can see, the contains an activity, a (wakeful) broadcast receiver and an intentservice, all in the same package. The activity gets started at launch, here's the code:
package com.example.broadcasttest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBroadcast(new Intent(this, TestReceiver.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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This succesfully triggers the onReceive function of TestReceiver.
package com.example.broadcasttest;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class TestReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Intent service = new Intent("com.example.broadcasttest.MonitorService");
Intent service = new Intent(context, MonitorService.class);
startWakefulService(context, service);
}
}
This is where things go wrong though, I placed a breakpoint in the onReceive function and it definitely gets called. However, the MonitorService class never gets reached. I placed a breakpoint in the onHandleEvent function, but it seems like it never gets that far. Here's the code for this class:
package com.example.broadcasttest;
import android.app.IntentService;
import android.content.Intent;
public class MonitorService extends IntentService {
public MonitorService(String name) {
super(name);
}
public MonitorService()
{
super("MonitorService");
}
#Override
protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TestReceiver.completeWakefulIntent(intent);
}
}
}
As you can tell from the commented line in the TestReceiver class, I've tried using an implicit intent instead of an explicit one. I've also read this question and tried everything mentioned there. Am I missing something here? I'm running this on an emulator (Nexus7 API L).
Is there anything I'm missing here?
There is no tag as <intentservice> in Application Manifest. IntentService is a subclass of Service, so you need to declare it as service in manifest.
Change
<intentservice
android:name="com.example.broadcasttest.MonitorService"
android:enabled="true" >
<intent-filter>
<action android:name="com.example.broadcasttest.MonitorService" />
</intent-filter>
</intentservice>
to
<service
android:name="com.example.broadcasttest.MonitorService"
android:enabled="true" >
<intent-filter>
<action android:name="com.example.broadcasttest.MonitorService" />
</intent-filter>
</service>
I am trying to create an Android app in Android Studio.
The app is mainly a background service to send some information to the server around every 15 seconds or so.
I have created an empty activity, boot receiver and a service class, but it doesn't work.
Could somebody help me, and explain why it doesn't work.
The relevant files:
MainActivity.java
package nl.robinvandervliet.robinsapp.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
finish();
}
}
BootReceiver.java
package nl.robinvandervliet.robinsapp.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, RobinsService.class));
}
}
RobinsService.java
package nl.robinvandervliet.robinsapp.app;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class RobinsService extends Service
{
private Runnable runnable = new Runnable()
{
#Override
public void run()
{
//Opening connection to the server.
while (true)
{
//Sending some data to the server.
//Sleeping for around 15 seconds.
}
//Dead code, should never reach this place.
}
};
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
new Thread(runnable).start();
Notification notification = new Notification.Builder(getApplicationContext()).setContentTitle("MyService is running!").setContentTitle("(more information later)").build();
startForeground(1, notification);
Toast.makeText(getApplicationContext(), "Service created!", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.robinvandervliet.robinsapp.app" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="nl.robinvandervliet.robinsapp.app.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="nl.robinvandervliet.robinsapp.app.BootReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="nl.robinvandervliet.robinsapp.app.RobinsService" android:exported="false" />
</application>
<uses-permission android:name="android.permission.BATTERY_STATS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Thanks, Robin.
Since you haven't implemented some parts yet I assume you just want it to run when you boot your device. Maybe take a look here. Adding an extra action in the manifest might solve your problem.
I am trying to open a web browser window onclick of a button.
My click event doesn't appear to be getting called. LogCat shows no errors or any evidence of it being called. I have a feeling this is due to me having 2 methods named 'onClick', but removing the second method causes an error. I can fix this error by making MainActivity abstract, but that crashes the app.
I feel this is a simple fix, but after pouring over documentation and several tutorials I cannot find the answer.
Code is below, followed by my manifest. Thanks in advance.
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
//displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(View v) {
// TODO Auto-generated method stub
// do something when the button is clicked
displayMessage("Loading broswer");
Uri uriUrl = Uri.parse("http://www.***.com/");
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
if(v.getId() == R.id.btnVisitWebsite) {
}
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
And the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
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>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
You have an OnClickListener but you didn't attach it to any button. Try
((Button) findViewById(R.id.your_button_id)).setOnClickListener(this);
EDIT: The other problem is, that you implemented DialogInterface.OnClickListener instead of View.OnClickListener in your Activity.
Remove the imports
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
And add
import android.view.View.OnClickListener;
You can also remove
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
after this.
Because you didn't associate the click event.
If you are binding it to button (or) something, you need to do bind it for 'this'
Example:
button.setOnClickListener(this);
To avoid confusion, you could also do it using the XML if you are not creating the view programatically. You can do something like this.
<Button android:width="20dp" android:height="20dp" android:onClick="openBrowser" />
and provide the method in your program as
public void openBrowser(View v)
{
/* do your stuff here */
}