I am trying to get current battery level using broadcast receiver with intentfilter ACTION_BATTERY_CHANGED having only one TextView in my xml and setting its text property to some string+integer variable that should hold value of BatteryManager.EXTRA_LEVEL. But app crashes everytime it try to boot.
Am i missing something?
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView tvcl=(TextView) findViewById(R.id.tvcl);
private BroadcastReceiver bcr=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int currentLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
tvcl.setText("Current Battery Level "+ Integer.toString(currentLevel) + "%");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IntentFilter bcFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(bcr,bcFilter);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
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>
The line
TextView tvcl=(TextView) findViewById(R.id.tvcl);
appears to be in the class definition and not in a method.
If so, then it will return null since the ContentView isn't set until OnCreate whereas this definition occurs at object creation time.
Related
I have two app - MyApplication and FirstApp. There's is a button in MyApplicaton on click of which I am navigated to FirstApp.
Now, I want to read the contents of FirstApp using AccessibilityService.
My code goes like this for MyApplication-
MainActivity.java
package com.example.abc.myapplication;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,MyAccessibilityService.class);
startService(intent);
mButton = (Button) findViewById(R.id.click_me);
mButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc.firstapp");
startActivity(launchIntent);
}
}
MyAccessibilityService.java
package com.example.aayushi.myapplication;
public class MyAccessibilityService extends AccessibilityService {
private AccessibilityServiceInfo info;
#Override
protected void onServiceConnected() {
Log.i("service connected","service");
info = new AccessibilityServiceInfo();
info.eventTypes=AccessibilityEvent.TYPES_ALL_MASK;
info.notificationTimeout=100;
info.feedbackType=AccessibilityEvent.TYPES_ALL_MASK;
info.packageNames = new String[]{"com.example.abc.firstapp"};
setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.i("onEvent----","yay");
Log.i("event-----------", event.toString());
//Log.i("source", event.ge)
}
#Override
public void onInterrupt() {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abc.myapplication">
<uses-feature android:name="android.hardware.fingerprint"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<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">
<service android:name=".MyAccessibilityService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/accessibility_config"/>
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
accessibility_config.xml
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="#string/accessibility_service_description"
android:packageNames="com.example.abc.myapplication"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFlags="flagDefault"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"
android:settingsActivity="com.example.abc.myapplication.MyAccessibilityService" />
The problem is after enabling accessibility on device, onServiceConnected() is not at all getting called.
For testing, I am using Android 8.0.0 , API 26.
It looks like you're trying to start your accessibility service from within your activity. You can't do this. You must start your accessibility service from the accessibility services menu. Settings > General > Accessibility. You also most get rid of the code that attempts to start your service from within your activity.
I have sent a broadcast here:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("com.example.administrator.broadcasttest.MY_BROADCAST");
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
// Toast.makeText(MainActivity.this, "You have send a broadcast just now.", Toast.LENGTH_SHORT).show();
}
});
}
}
But i can't receive it in my broadcast receiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver",
Toast.LENGTH_SHORT).show();
}
And here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.broadcasttest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.administrator.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In addition, my andriod version is 7.1.1, and my API version is 26.
I have tried many ways to solve it, but none worked.
I am searching for a long time to no avail
Please help or try to give me some ideas about how to achieve this.Thanks in advanced.
You cannot have more than one public class in a java file. Move your broadcast receiver class into a separate file.
I usually register receivers via XML AND code.
Try to register it:
BroadcastReceiver whatever = new MyBroadcastReceiver();
registerReceiver(whatever, intentFilter);
//Intentfilter is the intent you get in MyBroadcastReceiver
Hope it helps.
EDIT: DO NOT FORGET TO UNREGISTER IT:
unregisterReceiver(whatever);
I wanted to intercept an incoming message so I created a class extending BroadcastReceiver(as given here) it worked but as I wanted to control the receiver(stop it when required) I implemented this but now when I exit the activity the receiver doesn't work.
How to implement the receiver such that it can be controlled and receive broadcast when the activity is not running?
Mainactivity
public class MainActivity extends Activity {
Button StopB;
IntentFilter STARTER;
final BroadcastReceiver MSgR=new BR();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StopB=(Button) findViewById(R.id.button1);
final BroadcastReceiver MSgR=new BR();
STARTER=new IntentFilter();
STARTER.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(MSgR, STARTER);
StopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("Pressed", "UNRGSTR");
unregisterReceiver(MSgR);
}
} ) ;
}
BR.java
public class BR extends BroadcastReceiver{
String TAG="DELETE BLOCK";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// do something here
}
Manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.delete_sms_2.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="BR"></receiver>
</application>
</manifest>
define when the receiver will start, you define when activity start then recive work, you need to change in menifest file , as like in this intent filter when sms recived, as like you change it accourding to ur need thanks
<receiver android:name=".HellowordActivity" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
I m trying to start an IntentService from the main activity of y application and it won't start. I have the service in the manifest file. Here's the code:
MainActivity
public class Home extends Activity {
private LinearLayout kontejner;
IntentFilter intentFilter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
kontejner = (LinearLayout) findViewById(R.id.kontejner);
intentFilter = new IntentFilter();
startService(new Intent(getBaseContext(), HomeService.class));
}
}
Service:
public class HomeService extends IntentService {
public HomeService() {
super("HomeService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_LONG).show();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.salefinder"
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=".Home"
android:label="#string/title_activity_home" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".HomeService" />
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
How can I make it work?
onHandleIntent gets called from a background thread. You can't modify the UI, or in this case, make Toast from outside the UI thread. So, I wouldn't expect anything to happen with your service.
Just try writing something out with Log.d() to see if your service is getting called.
It seams that android cached a bad version of the app - I forced closed it and started it again, and it worked...
I am trying to read an NFC tag, when I click a button on my app. Currently I am able to detect the tag in default mode (Tag app installed in Nexus phone). but I am not able to get to display the activity chooser through which I want to launch my tag
public class NFC_button extends Activity
{
protected IntentFilter ifilter ;
private NfcAdapter adapter;
private BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
{
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] ndefmessages;
if(messages != null)
{
ndefmessages = new NdefMessage[messages.length];
for(int i = 0;i<messages.length;i++)
{
ndefmessages[i] = (NdefMessage)messages[i];
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
adapter=NfcAdapter.getDefaultAdapter(this);
ifilter = new IntentFilter();
ifilter.addAction("android.nfc.action.NDEF_DISCOVERED");
ifilter.addCategory("android.intent.category.LAUNCHER");
}
#Override
protected void onResume() {
registerReceiver(receiver, ifilter);
super.onResume();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nfc.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.NFC"/>
<uses-feature android:name="android.hardware.nfc" android:required="true"/>
<uses-sdk android:minSdkVersion="10"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".NFC_ExampleActivity"
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=".NFC_button">
</activity>
</application>
First of all the I don't think the BroadcastReciver is the correct way to read a tag. And other mistake that i see is that your intent filter has a category:
android.intent.category.LAUNCHER
but the correct category should be:
android.intent.category.DEFAULT
I would suggest that you add the intent filter to the manifest of the activity that you want to start when you touch the tag like this:
<activity android:name=".NFC_button">
<intent-filter >
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
and move the code that you have in the onReceive method of BroadcastReceiver to onCreate of the NFC_button activity.
If there is no specific reason that you want to use BroadcastReceiver, this will solve your tag reading problem.