Start/Stop Notificationlistener - Java for Android App Development

Hello,
At the moment I have a big problem, how can i stop the Notificationlistener?
Is there a good way to start and stop it at a specific time?
Or is there another possibility to add the Notificationlistener to my project?
thanks for help
Manifest:
Code:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="test.myapplication" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="test.myapplication.MainActivity" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".NLService" android:label="@string/app_name" android[emoji14]ermission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> <intent-filter> <action android:name="android.service.notification.NotificationListenerService" /> </intent-filter> </service> </application> </manifest>
NLService:
Code:
public class NLService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.v("NL","START");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v("NL","STOP");
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationPosted");
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
}
}
Main:
Code:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setContentTitle("My Notification");
ncomp.setContentText("Notification Listener Service Example");
ncomp.setTicker("Notification Listener Service Example");
ncomp.setSmallIcon(R.drawable.ic_launcher);
ncomp.setAutoCancel(true);
nManager.notify((int)System.currentTimeMillis(),ncomp.build());
}
else if(v.getId() == R.id.btnClearNotify){
Log.v("NL", "CLEAR");
}
}
}

From a brief overview of some questions regarding this issue, it seems it stopping NotificationListenerService using stopSelf() or stopService(Intent intent) not always work as expected (you should try this though).
A simple workaround is to move the actual logic to another service, and have the NotificationListenerService start it only if the conditions for handling it are met.

how can i do this i tried it but i wasn't succesful. could you give me an example?

joko15 said:
how can i do this i tried it but i wasn't succesful. could you give me an example?
Click to expand...
Click to collapse
In your original service onStartCommand pass the intent you receive (or create one yourself) and start the workaround service with it:
Code:
startService(new Intent(this, YOUR_WORKAROUND_SERVICE_CLASS.class));
Handle the intent in the onStartCommand method of the workaround service.

will i have to change something in my manifest?
In my NLService I have to add the function onStartCommand what will i have to add in this function?

joko15 said:
will i have to change something in my manifest?
In my NLService I have to add the function onStartCommand what will i have to add in this function?
Click to expand...
Click to collapse
You'll need to add the new service to your manifest

and what will come in to onstartcommand function?

joko15 said:
and what will come in to onstartcommand function?
Click to expand...
Click to collapse
The intent you send it through startService command.
If you want to understand more about services, try this from Android Developer.

Related

Problem when updating a Widget by an activity

Hello all together,
i've got a little problem updating my widget.
I wanted to add a widget to an existing app (Static IP Toggle).
This app changes between DHCP and static IP configuration when started =>
app started -> DHCP
app started again -> static IP, and vice versa.
I got a request from a user of this app, that it would be nice if there would be a widget included, showing which mode is active (either DHCP or static IP), so I added the widget as follows:
Added lines, concerning the former version without widget, are highlighted in blue.
First I declared the Widget in AndroidManifest.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chemdroid.staticiptoggle"
android:installLocation="internalOnly" android:versionName="1.2" android:versionCode="3">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".StaticIPToggle"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
[COLOR="Blue"]<receiver android:name=".Widget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
</receiver>[/COLOR]
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
</manifest>
The AppWidgetProvider was declared in /xml/widget.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="72dp"
android:minHeight="72dp"
android:updatePeriodMillis="0"
android:initialLayout="@layout/widget_dhcp">
</appwidget-provider>
I created 2 layouts, one for DHCP, one for static IP. Included was an ImageButton for showing either DHCP or static IP.
Widget.java was created, for setting the specified layout and starting the activity for changing the settings:
Code:
package com.chemdroid.staticiptoggle;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.widget.RemoteViews;
public class Widget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int use_static_ip;
RemoteViews remoteViews;
try {
use_static_ip = Settings.System.getInt(context.getContentResolver(), Settings.System.WIFI_USE_STATIC_IP);
if (use_static_ip == 0) { //DHCP
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_dhcp);
} else { //static IP
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_static);
}
Intent call_activity = new Intent(context, StaticIPToggle.class);
PendingIntent pending_call_activity = PendingIntent.getActivity(context, 0, call_activity, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_icon, pending_call_activity);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
} catch (SettingNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
At last, the activity was changed to update the widget, after IP settings have been changed:
Code:
package com.chemdroid.staticiptoggle;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.provider.Settings;
import android.widget.Toast;
public class StaticIPToggle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int use_static_ip;
try { --> Code für Änderung der Config
[COLOR="Blue"]AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
ComponentName componentName = new ComponentName(getApplicationContext(), Widget.class);
int[] ids = appWidgetManager.getAppWidgetIds(componentName);
Intent update_widget = new Intent();
update_widget.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
update_widget.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
getApplicationContext().sendBroadcast(update_widget);[/COLOR]
} catch (SettingNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
But now I have this bug:
If the widget is onClicked, it shows the energy-settings-widget for a short period (~0,5sec-1sec) before the desired widget is shown. A screenshot is attached.
First there's the widget as in the left picture, then changes to the middle picture and either stays there or changes to the right picture after ~0,5-1sec.
Unfortunately I can't see any mistake in the code, do you?
Greetz Oli
Nobody here who can help me? :-/
I really can't see any mistake in my code, but what's the problem there?
Solved the problem by sending an own intent that is received from the widget -> onReceive: call onUpdate

webview help

I am having trouble creating a webview app for my already mobile ready site.
I keep getting this error in the emulator:
The application window cleaning forums (process com.windowcleaningforums) has stopped unexpectadly
The app never actualy loads just goes straight to this.
Basically i already have my sites mobile ready and browsing to them on your mobile works fine, but would like to put these into apps.
With a back, forward and refresh button when hitting menu button on phone.
(I am not sure what i need to add these yet but any advice would be great)
My project is set as bellow
Application name: Window Cleaning Forums
Package name: com.windowcleaningforums
Create activity: windowcleaningforums
Mini SDK version: 4
windowcleaningforums.java
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.windowcleaningforums.co.uk");
mWebView.setWebViewClient(new HelloWebViewClient());
}
}
Main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<webView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.windowcleaningforums"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".windowcleaningforums"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
I am very new and im not quite sure what is causing it any help would be great. Thanks
I get this if that is any help i am not sure what it means though.
[2011-01-12 22:35:07 - DeviceMonitor]Sending jdwp tracking request failed!
This is the log if that helps also i really could do with some help peeps, nobody seems to want to. I know i am new and prob asking stupid questions but how am i supposed to learn if i dont ask questions.
Hi cyberpedz,
Probably just a typo but in your main.xml the WebView tag should have a capital "W" like so:
<WebView xmlns:andro...
You did the right thing looking in the log. That's what helped to figure this one out: there was an exception stack trace in the log. (Keep an eye out for the "AndroidRuntime" tag)
Thanks i have changed that but no difference.
I do have a red dot over a hellowebview class though
When viewing windowcleaningforums.java and looking at the right in outline i have a read dot over hellowebviewclient
Could it be something to do with this bit of code?
Code:
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Try moving the
Code:
//@Override
just before onCreate and uncomment it.
Also Java classes should start with a capital (public class Windowcleaningforum). Make sure you modify the Manifest accordingly.
Ok finally i have it working, it was me being blind i missed a webView now changed to Webview and all works thanks so much.
Now i am trying to get a loading progress bar or even better spinning circle.
What code would i need for this and where abouts in my java bellow would i fit it in?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.WebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.windowcleaningforums.co.uk");
mWebView.setWebViewClient(new HelloWebViewClient());
}
}
Anyone know how to get the spinning circle while pages loads? and how to imput into my code above?
Would be a great help
Ok finally i have a running webview in the market what i would like to do now is add a soft menu for a back, refresh and forward button what code do i need and where would i put it in my java below?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity
{
final Activity activity = this;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
}
So why is it no body wants to help is it the way i ask? is it that developers think they are above the noob? or you really cant b bothered!!
I have even offered to pay for help in the past yet nobody is interested maybe it is that no one really knows the answers.
cyberpedz said:
So why is it no body wants to help is it the way i ask? is it that developers think they are above the noob? or you really cant b bothered!!
I have even offered to pay for help in the past yet nobody is interested maybe it is that no one really knows the answers.
Click to expand...
Click to collapse
It's not that developers can't be bothered, but generally they will have other things to do than help out others. The thing is, you're asking on help for pretty basic stuff. This is something that you should know already, and if don't I suggest you should read through Android's developer website one more time and look at the API examples/demos too.
Hints for your problem; Add the buttons as a merge layout in your XML and then link them with your web view, or add them as menu options. Googling for both will surely give you enough results to get you on your way, these are pretty basic things you want to do after all.

Widget for turning on/off camera flashlight (Android , Eclipse)

I've seen Widget for turning on/off camera flashlight in android but for some unknown reasons its not working I would really appreciate it if someone could help me. I've been trying for over 2 days.There isn't any error in eclipse.
QFlashlightWidgetProvider class:
Code:
public class QFlashlightWidgetProvider extends AppWidgetProvider {
[user=439709]@override[/user]
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Intent receiver = new Intent(context, QFlashlightWidgetProvider.class);
receiver.setAction("COM_FLASHLIGHT");
receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.qflashlight_appwidget);
views.setOnClickPendingIntent(R.id.flashtoggle, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
}
class QFlashlightWidgetReceiver
Code:
class QFlashlightWidgetReceiver extends BroadcastReceiver {
private static boolean isLightOn = false;
private static Camera camera;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.qflashlight_appwidget);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, QFlashlightWidgetProvider.class),
views);
Toast.makeText(context, "Turning Cam On", Toast.LENGTH_SHORT).show();
}
}
Manifest.xml
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
Code:
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/qflashlight_appwidget_info" />
</receiver>
<receiver android:name="QFlashLightWidgetReceiver">
<intent-filter>
<action android:name="COM_FLASHLIGHT"></action>
</intent-filter>
</receiver>
P.S: I removed the code for turning the cam on/off and put a toast message but even the toast message isn't showing.The widget should display a toast message when clicked(I will put the code to turn on the flash when i succeed in making it display a toast)

Stackview Widget - Items not loading

I've tried to create simple dialer widget that will get contacts from contact book, put them into stackview and when clicked create a popup where you can call or create a message. I worked well as an application, but when I turned it into actual widget, I've encountered something weird. Despite all the methods firing, the items are not updated and stay on loading layout.
I've compared it to the example, tried to switch parts of code and nothing works. Even funnier, my code works perfectly when I put it in example widget, but example code doesn't work in mine. The same thing happens for listview and gridview. Is there any other file I should edit?
I provide the code, layouts and manifest. Logcat shows all methods firing in right order, so there's nothing to see there.
WidgetProvider.java
Code:
public class WidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds){
Log.d("WIDGET", "Called onUpdate()");
for (int i = 0; i < appWidgetIds.length; ++i){
// Set up the intent that starts the StackViewService, which will
// provide the views for this collection.
Intent intent = new Intent(context, WidgetService.class);
// Add the app widget ID to the intent extras.
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
// Instantiate the RemoteViews object for the app widget layout.
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setRemoteAdapter(R.id.stackView, intent);
rv.setEmptyView(R.id.stackView, R.id.emptyView);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
Log.d("WIDGET", "Widget updated");
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
WidgetService.java
Code:
package com.chmis.superdialer;
import java.util.Collections;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
public class WidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
}
}
class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
Context context;
Intent intent;
public StackRemoteViewsFactory(Context applicationContext, Intent intent) {
this.context = applicationContext;
this.intent = intent;
}
@Override
public void onCreate() {
Log.d("SERVICE", "Called onCreate()");
//Get contact Cursor
Cursor contactCursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
//Get contacts from cursor, store them as Contact objects inside ArrayList
while (contactCursor.moveToNext()) {
String name = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
long id = contactCursor.getLong(contactCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
Contact.array.add(new Contact(name, phone, id));
}
//Sort contacts by name
Collections.sort(Contact.array, new ContactComparator(Contact.JOHN_SMITH));
}
@Override
public RemoteViews getViewAt(int position) {
Log.d("SERVICE", "Called getViewAt(" + position + ")");
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.contactNameTextView, Contact.array.get(position).getDefaultName());
// Return the remote views object.
return rv;
}
@Override
public int getCount() {
Log.d("SERVICE", "Called getCount(), returned " + Contact.array.size());
return Contact.array.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 0;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onDataSetChanged() {}
@Override
public void onDestroy() {
Contact.array.clear();
Log.d("SERVICE", "Called onDestroy()");
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<StackView
android:id="@+id/stackView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:loopViews="true" />
<TextView
android:id="@+id/emptyView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/transparent"
android:textStyle="bold"
android:textColor="#ffffff"
android:text="@string/no_contacts" />
</FrameLayout>
contact_stack_item
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/transparent_dark" >
<ImageView
android:id="@+id/contactPhotoImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/contact_image_description"
android:src="@drawable/contact_photo_default" />
<TextView
android:id="@+id/contactNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/contactPhotoImageView"
android:layout_alignLeft="@+id/contactPhotoImageView"
android:layout_alignRight="@+id/contactPhotoImageView"
android:background="@color/transparent_dark"
android:gravity="center_horizontal"
android:text="@string/contact_name_placeholder"
android:textColor="@android:color/white" />
</RelativeLayout>
manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chmis.superdialer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application android:label="@string/app_name" >
<receiver android:name="WidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/app_widget_provider_info" />
</receiver>
<service
android:name="WidgetService"
android:exported="false"
android:permission="android.permission.BIND_REMOTEVIEWS" />
</application>
</manifest>
@edit I've copied the whole service code again and now it decided to work. I don't know anything anymore.

Example of an app that runs as a service(and does some work periodically in a thread)

Hi there,
Can you share please a link to simple example of an app that runs as a service(and does some work periodically in a thread) and started at boot? It should not be an activity. Thank you.
Not a link, but should be good to start:
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="your.package" android:versionCode="1" android:versionName="1.0" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoDisplay">>
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".YourService" />
</application>
</manifest>
Here you receive broadcast (Intent) dispatched by the system on boot.
Receiver.java
Code:
public class Receiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
Intent i = new Intent(this, YourService.class);
startService(i);
}
}
Service should do your work.
YourService.java
Code:
public class YourService extends Service {
@Override public void onStart(Intent intent, int startId) {
// do some work here
}
}
This is a simple implementation. To make it run periodically, try to use AlarmManager with IntentService.
I wrote an app that unfortunately doesn't start at boot. I am also aware (theoretically) of the change in policy of BroadcastReceiver from 3.1 version. But I could not catch what the point is, how I register the service from user activity?
public class AlarmScheduleActivity extends Activity {
// UI parameters
Button btnStart;
Button btnStop;
@override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStart = (Button)findViewById(R.id.button1);
btnStop = (Button)findViewById(R.id.button2);
}
public void btnStartSchedule(View v) {
try {
AlarmManager alarms = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(),
AlarmReceiver.class);
intent.putExtra(AlarmReceiver.ACTION_ALARM,
AlarmReceiver.ACTION_ALARM);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 2000, pIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void btnCancelSchedules(View v) {
Intent intent = new Intent(getApplicationContext(),
AlarmReceiver.class);
intent.putExtra(AlarmReceiver.ACTION_ALARM,
AlarmReceiver.ACTION_ALARM);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, 1234567,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
alarms.cancel(pIntent);
}
}
public class AlarmReceiver extends BroadcastReceiver {
public static String ACTION_ALARM = "com.alarammanager.alaram";
@override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String action = bundle.getString(ACTION_ALARM);
if (action.equals(ACTION_ALARM)) {
Log.i("Alarm Receiver", "If loop");
Intent inService = new Intent(context,TaskService.class);
context.startService(inService);
}
}
}
public class BootBroadcastReceiver extends BroadcastReceiver {
 @override
public void onReceive(Context context, Intent intent) {
Intent alarmIntent = new Intent("com.company.android.AlarmReceiver");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(),
2000, pi);
}
}
public class TaskService extends IntentService {
public TaskService() {
super("TaskService");
// TODO Auto-generated constructor stub
}
 @override
protected void onHandleIntent(Intent arg0) {
// Do some task
Log.i("TaskService", "Service running: yes-yes-yes");
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".AlarmScheduleActivity"
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=".BootBroadcastReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver
android:name="AlarmReceiver"
androidrocess=":remote" >
</receiver>
<service android:name=".TaskService" >
</service>
</application>
Any idea?

Categories

Resources