Widget for turning on/off camera flashlight (Android , Eclipse) - Java for Android App Development

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)

Related

[Q] How to create youtube start/stop function for video recording function? HELP!

Is there a way to get the entire surfaceView screen to function like a button which start/atop a video recording process whenever it sees fit by the user? The function is somewhat similar to youTube's start/stop play function but instead this time it is used to start/stop the video recording process.
Is the code suppose to be coded in the .xml file or my .java file to accomplish the task? Sorry i'm rather new to android/java and given only 6 more weeks to finish this assignment by my lecturer to complete an app which act like a car blackbox yet i'm a total beginner in programming... Any help would be appreciated... Thanks in advance...
This is what i tried so far, can someone guide me i'm really in a desperate situation, PLEASE HELP ME :'(
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My serviceRecording.java file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
private boolean RecordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
RecordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (RecordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
RecordingStatus = false;
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.unlock();
}
catch(Exception e){
ServiceCamera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
RecordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
ServiceCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
RecordingStatus = false;
}
}
My .xml file
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:text="Video"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Button>
<Button
android:text="Setting"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
></Button>
<Button
android:text="Back"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
></Button>
<Button
android:text="Start"
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
></Button>
<Button
android:text="Stop"
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
></Button>
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="480dp"
android:layout_height="320dp"
android:layout_toRightOf="@+id/button2"
></SurfaceView>
<TextView
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/button2"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
></TextView>
</RelativeLayout>
</FrameLayout>
someone answer me please, i really need your guys help...
why isn't someone answering is my question so unwelcoming?
Haiz can anyone help me, i really need some guidance and help here...
You want to
Code:
implement OnClickListener
add method
Code:
onClick(View v)
then you want to add
Code:
surfaceView.setOnClickListener(this);
When surface is clicked onClick is called
By any chance could you explain how should i implement the above said functions into my codes because like implement onclicklistener and this and that i don't quite understand where should i place these above codes??
And how should this above function handle my startService and stopService intents? Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked? Could you guide me in this in much more details, sorry if i'm kinna stupid to understand your explanations...
Ok
CameraTest.java
Add
Code:
public void onClick(View v){
}
Replace
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
with
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback, OnClickListener {
After
Code:
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
Add
Code:
surfaceView.setOnClickListener(this);
how should this above function handle my startService and stopService intents?
Click to expand...
Click to collapse
Your intent function calls the CameraTest.surfaceView so everything will work with whatever code you put in the onClick function.
Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked?
Click to expand...
Click to collapse
Need better explanation on what you are asking.
The last part is probably like how when you tap a YouTube video on the video itself it kinda flashes the play or pause button over the video.
Sent from my MIUI SCH-i500
Which of these should i import?
Code:
import android.content.DialogInterface.OnClickListener;
import android.view.View.OnClickListener;
Should i put startService and stopService intent together, but it seems not appropriate as both statement seems to conflict each other when i click to start/stop my service? Or i need add some sort of if.. else logic statement to differentiate the start/stop service alternating when being clicked?
Code:
public void onClick(View v){
startService(new Intent(getApplicationContext(), ServiceRecording.class));
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
Yes that was what i meant for the last part of my question the sort of effect it will display when being clicked, sorry if i could not explain well which might cause you some confusion.. Thanks for your help
Or should i be implementing some sort of imagebutton to emulate the above effect i mention or is there some other way to do it?
Can someone answer me??
Can someone please guide me on my above problem to get the result similar to what was like youtube??

Gmail Text Cloud Widget

ive been enamored by some of the more simple text based widgets as of late (like simplistic text and clockr) and decided to try to make a widget based on that design for gmail. it will display who the email is from in a text cloud where the most recent email is the largest with each subsequent email getting smaller. if the email is unread it will be bold, if not then it will be regular text.
my background is in making java apps for the command line and of a more linear layout. so i am learning android dev as i go. because i am learning as i go i am starting at the most basic and moving on. i have a widget with a text box that displays '0'. (yay! i know impressive). now i want to make the text increment by 1 every 1 second. (yes not very useful, but very useful for learning.) i want to do this with an AlarmManager. does the AlarmManager have to be in a service, or an adjacent activity, or could there be a static AlarmManager in my AppWidgetProvider class? i found some examples but they are all pretty complex. i want to start super simple and move towards advanced.
after that then i will do the same increment except each number will be added as a new textbox and the previous will decrease in size. and so on and so on.
any help would be greatly appreciated.
-Tyler
so i understand that a Handler is better for these small tics of times but doing this project is a learning excersise. let me show you what i have so far.
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsb.gmailinboxtextcloud"
android:versionCode="1"
android:versionName="1.0">
<application android:label="GmailInboxTextCloud" android:icon="@drawable/gitc_icon">
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".GITextCloud" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<!--
<intent-filter>
<action android:name="INCREMENT_COUNT_UPDATE" />
<action android:name="RESET_COUNT_UPDATE" />
<action android:name="PAUSE_COUNT_UPDATE"/>
</intent-filter>
-->
<meta-data android:name="android.appwidget.provider" android:resource="@xml/gitc_widget"/>
</receiver>
</application>
<service android:enabled="true" android:name=".AlarmService" />
</manifest>
my widget class
GITextCloud.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private int count = 0;
@Override
public void onEnabled(Context context) {
//super.onEnabled(context);
count = 0;
context.startService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onEnabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onDisabled(Context context) {
//super.onDisabled(context);
count = 0;
context.stopService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onDisabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onReceive(Context context, Intent intent) {
//super.onReceive(context, intent);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "[" + count + "]");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
manager.updateAppWidget(cName, rv);
count++;
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
}
my service that runs an AlarmManager
AlarmService.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
* Created by IntelliJ IDEA.
* User: Tyler
* Date: 4/16/11
* Time: 6:34 PM
*/
public class AlarmService extends Service {
private AlarmManager am;
private PendingIntent pendingIntent;
// public static String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
// public static String RESET_COUNT_UPDATE = "RESET_COUNT_UPDATE";
// public static String PAUSE_COUNT_UPDATE = "PAUSE_COUNT_UPDATE";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
am.cancel(pendingIntent);
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
setRepeatingAlarm(GITextCloud.class);
}
public void setOneTimeAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
}
public void setRepeatingAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);
}
}
what ends up happening is that my widget just shows [0] in white and 60sp big. never changes. and my toasts in the service never show up on the screen. am i starting the service wrong?
Is this just a stupid question or does no one know the answer? Cause if no one knows then nvm, wrong place to ask...
Its from my damn phone!!!
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Gene Poole said:
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Click to expand...
Click to collapse
yep, that determines how often the ACTION_APPWIDGET_UPDATE intent gets sent.
my gitc_widget.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="1000"
android:initialLayout="@layout/main">
</appwidget-provider>
buuut. after android 1.6 or maybe 1.5 that android:updatePeriodMillis tag defaults to 30minutes. which is why an AlarmManager must be used for anything less than 30min updates. and since i dont want to wait 30mins to know if my code works i need my service to start.
i have determined that my service never starts. it isnt shown in the running services on my android phone and the toasts from it never show. anyone know why the service isnt started?
As mentioned earlier, I don't know a lot about appwidgets, but they are incredibly difficult to debug and I've had to reboot the phone at times to get past bugs in my code, so don't be so sure that your service isn't running. First, I don't think AppServices show up in the "running services" tab, and second, I don't think toasts from a non-activity show up on the screen. I could be wrong about this, so don't take it as gospel. Try using Log() instead of Toast for debugging.
Also, I don't see anything in your code that sends an update to the appwidget. I think something in your service should eventually call GITextCloud.updateAppWidget().
Thanks for working with me. In my AlarmService class in the onStarted method i call the setRepeating() method that gets passed a class with wich it makes an intent that the AlarmManager should use to trigger the onRecieve() method in my GITextCloud class. I will look into the log(), thats a good idea. And i will be trying to setAction() on that intent and then specifically catch it in the onRecieve() method
Thanks for giving me something to think about
Its from my damn phone!!!
i made some edits and ran into a problem where my intent was caught be onReive() but the local variable called count never incremented... this is crazy! a block of code that would execute whenever a particular intent was recieved never did what i wanted:
count++;
refreshWidgets();
Toast.makeText(.... some indication this was done ...);
the toast was always displayed but the count never incremented. i thought the refreshWidgets method was bunk so i manually set the count in the method... everything was good... then i make a toast after the count++ to display count. count never incremented. well after messing around i found that i had count as a
private int count
i changed it to a
private static int count
and it worked! weird...
this is my final code that makes a number on a widget increment every couple of seconds. note: setting a repeating alarm with the AlarmManager for a small amount of time did not work. i had to make a nested one time alarm that kept rearming itself. and i got rid of the service cause some of the debuging tools in cm7 said it never started. cross that bridge when i get there....
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private static int count = 0;
private static int widgetCount = 0;
public static final String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
count = 0;
setOneTimeAlarm(this.getClass(), context);
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals("android.appwidget.action.APPWIDGET_ENABLED")) {
} else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_DISABLED")) {
} else if (intent.getAction().equals(INCREMENT_COUNT_UPDATE)) {
count++;
refreshViews(context);
Toast.makeText(context, "widget #" + widgetCount, Toast.LENGTH_SHORT).show();
if (widgetCount != 0) {
setOneTimeAlarm(this.getClass(), context);
}
} else {
//Toast.makeText(context, "count = " + count + " | " + intent.getAction(), Toast.LENGTH_LONG).show();
}
}
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private void refreshViews(Context context) {
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "" + count);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
widgetCount = manager.getAppWidgetIds(cName).length;
manager.updateAppWidget(cName, rv);
}
private void setOneTimeAlarm(java.lang.Class<?> cls, Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(INCREMENT_COUNT_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (3 * 1000), pendingIntent);
}
}

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?

[SOLVED] Lockscreen Widget forgets onUpdate init code after reopening the lockscreen

I made a simple widget, which has a few buttons. In order to make those buttons work, I use RemoteViews.setOnClickPendingIntent in the onUpdate method of the AppWidgetProvider. Works fine, as long as I place the widget only on the homescreen. But when using the widget on the lockscreen, I have the following problem:
Placing the widget on the lockscreen and immediately clicking the buttons works perfectly. But after closing the lockscreen and reopening it, the buttons don't work anymore. It seems like the widget had "forgotten" everything from the init stuff in the onUpdate method.
So, does somebody know how to fix this?
Some code snippets:
Code:
public class WidgetProvider extends AppWidgetProvider {
private static final String BUTTON_ALL_OFF = "buttonAllOff";
private RemoteViews remoteViews;
private ComponentName watchWidget;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetProvider.class);
remoteViews.setOnClickPendingIntent(R.id.buttonAllOff, getPendingSelfIntent(context, BUTTON_ALL_OFF));
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String action = intent.getAction();
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetProvider.class);
if (BUTTON_ALL_OFF.equals(action)) {
Log.d("test", "clicked");
//do fancy stuff
}
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_layout"
android:minHeight="700dp"
android:minWidth="300dp"
android:resizeMode="vertical"
android:updatePeriodMillis="0"
android:widgetCategory="home_screen|keyguard" >
</appwidget-provider>
Fixed it by adding the clicklistener also in the onReceive method

[Q] nullpointer and wrap_content problems

Hello there
I got 2 problems:
Firstly, if I launch the following code on my device, I'm getting a nullpointer, and I got no idea why. ( I know it's sorta basic stuff)
Secondly, I want toset the screen height and lenght to wrap_content, it's red marked in the code...that is also not working..
Could you maybe help out a noob?
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
int y = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
For the wrap_content one, you need to set that property to the view that holds the integer text, you can't set a height and width properties to an integer, only a view or other widgets such as buttons. So for you you should set the properties of the view with ID start_time to wrap_content for width and height - recommend doing this in the layout XML instead of java code.
I'm guessing that if you sort that out your null pointer will disappear.
Additionally in your public onClick(View v) method you should check the ID of the view before doing any function code, this means you can have multiple objects using the same listener.
So this:
Code:
@Override
public void onClick(View v) {
Random r = new Random();
... etc
Should become this:
Code:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_time:
Random r = new Random();
... etc
tahnks @Jonny for your answer, I changed the code, but now, my button isn't placed randomly on each click anymore, and I'm getting the nullpointer again. have a look:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(+1);
int y = r.nextInt(+1);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.wrap_content);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the xml
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.asddd.af.Game" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
thank you. I'm really happy, there exists such great help
i have now changed the view start_time to a button...because it actually IS a button (im stupid) but now, when I click on the button, it moves completely out of the screen, and if not, instead of getting the time, the app stopps again with nullpointer. It should stay in the screen, placed randomly on click and after some clicks, I want to recieve the elapsed time. what is this?
code:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(R.id.wrap_content);
int y = r.nextInt(R.id.wrap_content);
long startTime = SystemClock.elapsedRealtime();
i++;
Button b = (Button) findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the xml:
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="chdfss.dsfwegg.trhhGame" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</View>
</RelativeLayout>
I'm not familiar with the nextInt() function (I can look it upp later when I'm home) but I'm pretty sure you shouldn't be parsing a views ID as one of its conditions - eg you're doing nextInt(R.id.wrap_content), are you sure that's right?

Categories

Resources