everyone I am a beginner in android and creating my project android app,that receives broadcast and changes the wallpaper accordingly.The app changes the wallpaper on activating it,but when I generates the event by changing the date the app crashes and stops, would somebody help me with my code and tell me what is wrong with it? Please help Here is the code:
MyDateReceiver.class
package com.example.vinay.imager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by VINAY on 04-02-2018.
*/
public class MyDateReceiver extends BroadcastReceiver {
WeekService weekService;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_DATE_CHANGED)||intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
{
context.startService(intent);
System.out.println("Receiver Activated");
}
else
{
}
}
}
WeekService.class
package com.example.vinay.imager;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.io.IOException;
import java.util.Calendar;
public class WeekService extends Service {
private MyDateReceiver br;
public IntentFilter intentFilter;
private void dateChanger()
{
Calendar cd=Calendar.getInstance();
int day=cd.get(Calendar.DAY_OF_WEEK);
String []days=new String[]{"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
System.out.println("Today is"+days[day-1]);
final String k=days[day-1];
WallpaperManager wm=WallpaperManager.getInstance(getApplicationContext());
try {
if(k.equals("MONDAY")) {
wm.setResource(R.drawable.ab);
}
else if(k.equals("TUESDAY")) {
wm.setResource(R.drawable.dp);
}
else if(k.equals("WEDNESDAY")) {
wm.setResource(R.drawable.mm);
}
else if(k.equals("THURSDAY")) {
wm.setResource(R.drawable.nmn);
}
else if(k.equals("FRIDAY")) {
wm.setResource(R.drawable.nn);
}
else if(k.equals("SATURDAY")) {
wm.setResource(R.drawable.spr);
}
else
{
wm.setResource(R.drawable.spr2);
System.out.println("Hi"+k);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Registering to broadcast
br=new MyDateReceiver();
intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_TICK);
this.registerReceiver(br,intentFilter);
//
dateChanger();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopSelf();
System.out.println("Service Stopped..");
this.unregisterReceiver(br);
System.out.println("Receiver unregistered..");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
dateChanger();
return null;
}
}
Mainactivity.class
package com.example.vinay.imager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Intent servIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button act = (Button) findViewById(R.id.activate);
final Button deact = (Button) findViewById(R.id.deactivate);
ImageView wlp = (ImageView) findViewById(R.id.imView);
wlp.setImageResource(R.drawable.spr);
servIntent = new Intent(getApplicationContext(), WeekService.class);
act.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(act.getText().equals("Activate"))
{
startService(servIntent);
Toast.makeText(MainActivity.this,"Imager Activated",Toast.LENGTH_LONG).show();
}
}
});
deact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(deact.getText().equals("Deactivate"))
{
System.out.println("Service Terminated..");
stopService(servIntent);
Toast.makeText(MainActivity.this,"Service Terminated..",Toast.LENGTH_LONG).show();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vinay.imager">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".WeekService"/>
</application>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
</manifest>
activiyt_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vinay.imager.MainActivity">
<Button
android:id="@+id/activate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="208dp"
android:text="Activate"
app:layout_constraintBottom_toBottomOf="parent"
android:onClick="onClick" />
<Button
android:id="@+id/deactivate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Deactivate"
app:layout_editor_absoluteY="320sp"
tools:layout_editor_absoluteX="26dp"
tools:layout_editor_absoluteY="316dp"
app:layout_constraintTop_toBottomOf="@id/activate"/>
<ImageView
android:id="@+id/imView"
android:layout_width="161dp"
android:layout_height="157dp"
app:layout_constraintBottom_toTopOf="@id/activate"
android:layout_marginLeft="42sp"
android:layout_marginRight="42sp"
android:adjustViewBounds="false"
app:srcCompat="@android:drawable/gallery_thumb"
tools:layout_editor_absoluteX="112dp"
tools:layout_editor_absoluteY="44dp"
/>
</android.support.constraint.ConstraintLayout>
Logcatfile
02-10 01:50:10.558 2827-2827/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vinay.imager, PID: 2827
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.TIME_SET flg=0x24000010 } in com.example.vinay.imager.MyDateReceiver@5dbe656
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1132)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=android.intent.action.TIME_SET flg=0x24000010 }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1345)
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1374)
at android.app.ContextImpl.startService(ContextImpl.java:1358)
at android.content.ContextWrapper.startService(ContextWrapper.java:613)
at com.example.vinay.imager.MyDateReceiver.onReceive(MyDateReceiver.java:20)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1122)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
02-10 01:50:11.485 1315-2390/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
02-10 01:50:14.086 4436-4637/com.google.android.music:main E/GmsUtils: Failed to connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
02-10 01:50:15.371 2153-4134/com.android.settings E/BluetoothAdapter: Bluetooth binder is null
02-10 01:50:15.833 2472-3299/com.google.android.gms.persistent E/NetworkScheduler: ignoring stale queue check message
02-10 01:50:15.892 1762-3275/system_process E/BluetoothAdapter: Bluetooth binder is null
02-10 01:50:15.892 1762-3275/system_process E/BatteryStatsService: no controller energy info supplied
02-10 01:50:15.894 1762-3275/system_process E/KernelCpuSpeedReader: Failed to read cpu-freq: /sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state (No such file or directory)
02-10 01:50:15.894 1762-3275/system_process E/KernelUidCpuTimeReader: Failed to read uid_cputime: /proc/uid_cputime/show_uid_stat (No such file or directory)
02-10 01:50:15.895 1762-3275/system_process E/BatteryStatsService: modem info is invalid: ModemActivityInfo{ mTimestamp=0 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0, 0, 0, 0, 0] mRxTimeMs=0 mEnergyUsed=0}
02-10 01:50:45.654 2472-3299/com.google.android.gms.persistent E/NetworkScheduler: ignoring stale queue check message
02-10 02:00:01.544 2882-4875/com.google.android.gms E/MS_RegisterService: Exception during register request.
bdpz: PERMISSION_DENIED: The caller does not have permission
at bdpv.c(:com.google.android.gms@11947470:3)
at mpe.a(:com.google.android.gms@11947470:89)
at com.google.android.libraries.matchstick.net.SilentRegisterIntentOperation.a(:com.google.android.gms@11947470:253)
at com.google.android.libraries.matchstick.net.SilentRegisterIntentOperation.onHandleIntent(:com.google.android.gms@11947470:342)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms@11947470:2)
at crr.run(:com.google.android.gms@11947470:10)
at cro.run(:com.google.android.gms@11947470:9)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
The problem is that you're saying startService on the intent that you're receiving. This is the system intent that's broadcasted, not the intent to start your actual service. You'll need to create the proper intent to start your service.
Intent intent = new Intent(this, HelloService.class);
startService(intent);
Above will start HelloService. You'll need to change that to your own service.
In the future please include a stacktrace if you're getting crashes.