[Q] Broadcast Receivers - Android Q&A, Help & Troubleshooting

Hello, I am trying to create a broadcast receiver to detect when the screen was locked. I have it already working to detect when the the tablet was booted, but it won't work for the SCREEN_OFF action. Right now I just have it log any intents that where triggered and so far its only working for when the boot was completed.
Code:
package com.atlantis;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class broadcastReceiver extends BroadcastReceiver {
[user=439709]@override[/user]
public void onReceive( Context context , Intent intent ) {
Log.v( "atlantis" , "Hey this intent was triggered " + intent );
if ( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction()) ) {
Intent launchMain = new Intent ( context, MainActivityService.class );
context.startService( launchMain );
}
}
}
Android manifest:
Code:
<receiver
android:name = "com.atlantis.broadcastReciever"
android:enabled = "true"
android:exported = "false" >
<intent-filter>
<action android:name = "android.intent.action.ACTION_SCREEN_OFF" />
<action android:name = "android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Thanks

reply
did you write anything for screen lock intent... if yes display that code..

Related

Developer.Android.com First app crashed, please help me.

Hi,
I started following the 'Building your first app' on developer.android.com,
I like to do it but now after following the instructions fully it is crashing when you click the button.
I used as build platform Android 4.1, but that should not matter...
I included the codes down here, I hope anyone can help.
MyFirstActivity.java:
Code:
package com.example.lesson.one;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MyFirstActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// It crashes here, because here is the part where you push the button.
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java:
Code:
package com.example.lesson.one;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyFirstActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
}
AndroidManifest.xml:
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.MJV.lesson.one"
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=".MyFirstActivity"
android:label="@string/title_activity_my_first" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.myapp.DisplayMessageActivity" />
</application>
</manifest>
Strings.xml:
Code:
<resources>
<string name="app_name">Lesson ONE</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_my_first">MyFirstActivity</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
Main.xml:
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
I hope anyone can help me... Because Eclipse isn't giving any errors...
Edit 1: I tried it again, now without any things in the new activity. ( I mean without any code it must do ).
It still crashes, so its somewhere where it will start the new activity.
Edit 2: I ran a logcat, but I know now it cant find DisplayMessageActivity in androidmanifest.xml... Though its already added.
Edit 3: I found my problem, it was in androidmanifest.xml. I stated DisplayMessageActivity wrong! I read too quickly and skipped that part...

[Q] How do I use intent ACTION_TIME_TICK with BroadcastReceiver in a widget?

Hi, i'm try to create a simple clock that needs to be updated every minute, I want to use a BroadcastReceiver that listen the ACTION_TIME_TICK, however, it never launches, I have the action registered in the AndroidManifest:
Code:
<receiver android:name=".MainWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"></action>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_provider">
</meta-data>
</receiver>
<receiver android:name=".WidgetBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.TIME_TICK"></action>
</intent-filter>
</receiver>
The class MainWidget extends from AppWidgetProvider:
Code:
[user=439709]@override[/user]
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
//super.onUpdate(context, appWidgetManager, appWidgetIds);
updateWidget(context);
context.startService(new Intent(context, WidgetBroadcastReceiver.class));
}
public void updateWidget(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.activity_main_widget);
updateViews.setTextViewText(R.id.test, actualDate);
ComponentName myComponentName = new ComponentName(context, MainWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myComponentName, updateViews);
}
And the class WidgetBroadcastReceiver from BroadcastReceiver where I have this on the onReceive method:
Code:
if(action.equals(Intent.ACTION_TIME_TICK)){
Log.i("TICK", "WORKS");
}
But it never adds anything in the log, any help? Thanks in advanced, have a nice day!

Android widget not working on first click

have an android widget which is actually a button to start an activity.The widget works fine using this code but there is a small bug :
When I add the widget to the home screen , clicking it first time doesn't do anything , second time it works. Then it works normally from 1st click. And the same thing happens when the phone is restarted.Can someone help me solve this problem ??
MyWidgetIntentReceiver.java
public class MyWidgetIntentReceiver extends BroadcastReceiver {
@override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("Start")) {
onUpdate(context);
}
}
private void onUpdate(Context context) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
Intent configIntent = new Intent(context, WidgetFlash.class);
configIntent.putExtra("widget", 1);
configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent configPendingIntent = PendingIntent.getActivity(context,
0, configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_button,
configPendingIntent);
MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(),
remoteViews);
} }
MyWidgetProvider.java :
public class MyWidgetProvider extends AppWidgetProvider {
@override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo);
remoteViews.setOnClickPendingIntent(R.id.widget_button, buildButtonPendingIntent(context));
pushWidgetUpdate(context, remoteViews);
}
public static PendingIntent buildButtonPendingIntent(Context context) {
Intent intent = new Intent();
intent.setAction("Start");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, remoteViews);
}}
Widget in Manifest:
<receiver android:name="com.hybernect.flashlight.MyWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/demo_widget_provider" />
</receiver>
<receiver
android:name="com.hybernect.flashlight.MyWidgetIntentReceiver"
android:label="widgetBroadcastReceiver" >
<intent-filter>
<action android:name="Start" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/demo_widget_provider" />
</receiver>
The logcat shows nothing when I click first time. Please help !

[Q] GCM isn't working in my program

I decided to implement Google Cloud Messaging push notifications to notify users about news. I think it is topic messaging. For implement I took the Google GCM sample. I added all needed services, permissions and receiver in manifest. When I send a post request to Google GCM server, the response is true with message ID, but device doesn't notify. What is the matter? I tested in Bluestacks.
My manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="..."
xmlns:tools="..."
package="packagename" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="packagename.permission.C2D_MESSAGE" />
<permission android:name="packagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".activities.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.BiographyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_biography"
android:parentActivityName=".activities.MainActivity"
tools:ignore="UnusedAttribute" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MainActivity" />
</activity>
<activity
android:name=".activities.AboutActivity"
android:label="@string/title_about_app" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MainActivity" />
</activity>
<activity android:name=".activities.CrashReportDialog"
android:theme="@style/Theme.Dialog"
android:process=":error_report"
android:launchMode="singleInstance"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packagename" />
</intent-filter>
</receiver>
<service
android:name="packagename.AppGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="packagename.AppInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<service
android:name="packagename.RegistrationIntentService"
android:exported="false">
</service>
</application>
</manifest>
Main Activity:
Code:
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(GcmPreferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
Log.i("GCM", "Success!");
} else {
Log.i("GCM", "Error!");
}
}
};
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
GCM Listener Service:
Code:
public class AppGcmListenerService extends GcmListenerService {
private static final String TAG = "GCM";
/**
* Called when message is received.
*
* @param from SenderID of the sender.
* @param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
}
/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_app)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Instance ID Listener Service:
public class AppInstanceIDListenerService extends InstanceIDListenerService {
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
Registration Intent Service:
Code:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "GCM";
public RegistrationIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// In the (unlikely) event that multiple refresh operations occur simultaneously,
// ensure that they are processed sequentially.
synchronized (TAG) {
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.d(TAG, "GCM Registration Token: " + token);
subscribeTopics(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(GcmPreferences.SENT_TOKEN_TO_SERVER, true).apply();
}
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(GcmPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(GcmPreferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/**
* Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
*
* @param token GCM token
* @throws IOException if unable to reach the GCM PubSub service
*/
private void subscribeTopics(String token) throws IOException {
GcmPubSub.getInstance(this).subscribe(token, "/topics/global", null);
}
}
My POST request:
Code:
GCM Server
Content-Type:application/json
Authorization:key=mykey
{
"to": "/topics/global",
"data": {
"message": "This is a GCM Topic Message!",
}
}
I tested POST request. Android app tested on Bluestacks App Player. I noticed also the app is not in the running services in the settings. Also I tested the app on real phone, but notifications still does not come I have no use for a long time working on it. The issue is strangely. I checked my code - whole is true as in the Google sample and documentation.

''Error Type 3'' Activity Class {...} Not Found

Hi, every project I try to launch on my phone triggers the same error
-Error happens even on first install of the app on the phone..
-Error happens with any project at any point
-Yes, I tried to Clean, Rebuild, Invalidate and Restart and also manually delete the app on the phone
-Yes I tried adb kill and start
I think the error might be related to the phone and not my code as it's a sample blank code.
Any clue? Cant get to run anything at all....
Error
Code:
04/17 15:18:59: Launching app
$ adb shell am start -n "com.example.hellonothing/com.example.hellonothing.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Error while executing: am start -n "com.example.hellonothing/com.example.hellonothing.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.hellonothing/.MainActivity }
Error type 3
Error: Activity class {com.example.hellonothing/com.example.hellonothing.MainActivity} does not exist.
Error while Launching activity
Android Manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
package="com.example.hellonothing">
<application
android:allowBackup="true"
android:icon="[USER=22138]@Mipmap[/USER]/ic_launcher"
android:label="[USER=696546]@String[/USER]/app_name"
android:roundIcon="[USER=22138]@Mipmap[/USER]/ic_launcher_round"
android:supportsRtl="true"
android:theme="[USER=19691]@Style[/USER]/AppTheme">
<activity
android:name=".MainActivity"
android:label="[USER=696546]@String[/USER]/app_name"
android:theme="[USER=19691]@Style[/USER]/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Main Activity Code
Java:
package com.example.hellonothing;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
[USER=1021285]@override[/USER]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
[USER=1021285]@override[/USER]
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
[USER=1021285]@override[/USER]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
[USER=1021285]@override[/USER]
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thank you !

Categories

Resources