1
votes

I study about alarmmanager and autostart of my own application. I'd like have an invisible service (it's not correct name, sorry) that shows me a toast periodically (for test purpose).

The following code runs but not correctly. I click "button", activity disappear but nothing...

My code:

MainActivity

public class MainActivity extends Activity {

/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button buttonStart = (Button)findViewById(R.id.button1);
      buttonStart.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
    Intent myIntent = new Intent(getBaseContext(),
      MyScheduledReceiver.class);

    PendingIntent pendingIntent
     = PendingIntent.getBroadcast(getBaseContext(),
       0, myIntent, 0);

    AlarmManager alarmManager
      = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 10);
    long interval = 60 * 10; //
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
      calendar.getTimeInMillis(), interval, pendingIntent);
    finish();
  }});
  }

}


AutoStartNotifyReceiver

public class AutoStartNotifyReceiver extends BroadcastReceiver {
    private final String BOOT_COMPLETED_ACTION =   "android.intent.action.BOOT_COMPLETED";
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){

             Intent myIntent = new Intent(context, MyScheduledReceiver.class);
             PendingIntent pendingIntent = PendingIntent.getBroadcast(context,  0,     myIntent, 0);

             AlarmManager alarmManager =         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
             Calendar calendar = Calendar.getInstance();
             calendar.setTimeInMillis(System.currentTimeMillis());
             calendar.add(Calendar.SECOND, 10);
             long interval = 60 * 10;
             alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,         calendar.getTimeInMillis(), interval, pendingIntent);           
        }
    }
}

MyScheduledActivity

public class MyScheduledActivity extends Activity {

MediaPlayer player;

@Override
public void onCreate(Bundle savedInstanceState){ 
  super.onCreate(savedInstanceState);
  //Toast.makeText(getApplicationContext(), "Eseguo onCreate",     Toast.LENGTH_LONG).show();
  setContentView(R.layout.activity_main);

  player = MediaPlayer.create(this, R.raw.gabriel);
  player.start();



    Toast.makeText(this, "miao",Toast.LENGTH_LONG).show();

}

 }

 MyScheduledReceiver

 public class MyScheduledReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {

 Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
 scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 context.startActivity(scheduledIntent);
 }
 }

Manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".AutoStartNotifyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

{12-12 14:50:21.411: E/AndroidRuntime(865): FATAL EXCEPTION: main 12-12 14:50:21.411: E/AndroidRuntime(865): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.servi/com.example.servi.MyScheduledActivity}: java.lang.NullPointerException 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread.access$600(ActivityThread.java:123) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.os.Handler.dispatchMessage(Handler.java:99) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.os.Looper.loop(Looper.java:137) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread.main(ActivityThread.java:4424) 12-12 14:50:21.411: E/AndroidRuntime(865): at java.lang.reflect.Method.invokeNative(Native Method) 12-12 14:50:21.411: E/AndroidRuntime(865): at java.lang.reflect.Method.invoke(Method.java:511) 12-12 14:50:21.411: E/AndroidRuntime(865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 12-12 14:50:21.411: E/AndroidRuntime(865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 12-12 14:50:21.411: E/AndroidRuntime(865): at dalvik.system.NativeStart.main(Native Method) 12-12 14:50:21.411: E/AndroidRuntime(865): Caused by: java.lang.NullPointerException 12-12 14:50:21.411: E/AndroidRuntime(865): at com.example.servi.MyScheduledActivity.onCreate(MyScheduledActivity.java:22) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.Activity.performCreate(Activity.java:4465) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 12-12 14:50:21.411: E/AndroidRuntime(865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 12-12 14:50:21.411: E/AndroidRuntime(865): ... 11 more }

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servi"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.servi.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

<receiver android:name=".AutoStartNotifyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>
<receiver android:name="MyScheduledReceiver"></receiver>
<activity android:name="MyScheduledActivity"></activity>
</application>
</manifest>
2

2 Answers

1
votes

From http://www.androidsnippets.com/autostart-an-application-at-bootup

in AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>
[..]
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
[..]

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

You can use Timer class to schedule periodic task using TimerTask. Also You can use ScheduledThreadPoolExecutor class.

AlarmManager can be a good choice. The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

0
votes

Add a receiver in manifest... for your alarm recieving. In your case;

<receiver android:name=".MyScheduledReceiver">

</receiver>

I hope it will solve the problem

PS: your activity MyScheduledActivity will be started repeatedly twice in a second almost after every 600ms.... so don't do it... increase the interval :) OR do anything else to check maybe print logs or something for testing