Android, мой сервис не запускается - PullRequest
1 голос
/ 19 августа 2011

Я пытался настроить систему опроса, которая получает данные с сервера каждый день. Поэтому я планирую настроить AlarmManager таким образом, чтобы он запускал мой сервис каждый день 12:00, и сервис ищет некоторую информацию на моем сервере и отображает уведомление в строке состояния на основе данных с сервера.

Проблема в том, что я никак не могу запустить свой сервис. Сначала я попытался зарегистрировать PendingIntent в AlarmManager, но мой сервис так и не был запущен. А сейчас я просто пытаюсь запустить его с помощью startService.

Так что я делаю не так?

Манифест:

...
<application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".skosexActivity"
                  android:label="@string/app_name"
                  android:theme="@android:style/Theme.NoTitleBar"
                  android:screenOrientation="portrait">
            <service android:name=".notificationService"/>
            <receiver android:name="onBootReceiver" android:enabled="true">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter> 
</application>
...

Активность:

public class homeActivity extends Activity {

    static final boolean DEBUG = true;

    static final String TAG = "HomeActivity: ";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        mContext = getApplicationContext();

        //my try on AlarmManager

        AlarmManager mgr = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, notificationService.class);
        PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, 0);

        Calendar currentTime = Calendar.getInstance();
        currentTime.set(currentTime.get(Calendar.YEAR), 
                        currentTime.get(Calendar.MONTH),
                        currentTime.get(Calendar.DAY_OF_MONTH), 14, 44);

        /*mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                         SystemClock.elapsedRealtime() + 10000,
                         AlarmManager.INTERVAL_DAY, pi);*/

            //my try to just start it some how...
        Intent intent = new Intent(mContext, notificationService.class);

        Log.i("HomeActivity", "Trying to service");

        startService(new Intent(notificationService.class.getName()));
    }
...

Сервисный код:

package se.skosex.pr.skosexp1;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class notificationService extends IntentService {

    private static final int ID = 1;

    public notificationService()
    {
        super("NotificationService");
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Log.i("NotificationService", "It started!");

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.hagbard;
        CharSequence tickerText = "Kom och phesta med oss på Skövde sexmästeri kväll!";
        long when = System.currentTimeMillis();

        Notification notification = new Notification(icon, tickerText, when);

        Context context = getApplicationContext();
        CharSequence contentTitle = "Skövde Sexmästeri, test 2";
        CharSequence contentText = "Ikväll är det introdhisko och det betyder at du som nolla inte har några ursäkter att stanna hemma!";
        Intent notificationIntent = new Intent(this, eventActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);

        mNotificationManager.notify(ID, notification);
    }

}

Итак, что я не так понял?

Спасибо за любую помощь!

Ответы [ 4 ]

2 голосов
/ 17 февраля 2012

зарегистрируйте свой сервис в файле Android Manifest.xml

0 голосов
/ 22 февраля 2014

если вы пытаетесь получить доступ к серверу ... вам нужно добавить

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

до манифеста или, скорее всего, намерение молча провалится

0 голосов
/ 19 августа 2011

Опасность догадки ... возможно, вам не хватает необходимого разрешения?

http://developer.android.com/reference/android/Manifest.permission.html

String  SET_ALARM   Allows an application to broadcast an Intent to set an alarm for the user.
0 голосов
/ 19 августа 2011

Вероятно, это ваш вызов startService, попробуйте что-то вроде этого:

   Intent intent = new Intent(mContext, notificationService.class);
   startService(intent)

Похоже, ваш вызов startService () содержит тестовый код?

...