2018-11-14 08:15:02 gfuugff 阅读数 2242
  • Android 5.x视频课程

    采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。

    79746 人正在学习 去看看 李宁

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

使用AlarmManager搭配Receiver应该可以实现定时自动启动应用程序:

import android.app.Activity;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class StartTiming extends Activity {        public final String MYACTION = "android.intent.action.STARTMYAP";        /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                Button btn = (Button)this.findViewById(R.id.btnClose);        btn.setOnClickListener(new OnClickListener(){            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                StartTiming.this.finish();            }        });        AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);        Intent intent = new Intent(MYACTION);        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 1);        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+15000, pi);//15秒钟以后启动    }}   
import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class AlarmReceiver extends BroadcastReceiver{    public final String MYTAG = "Ray";    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        Log.v(MYTAG,"I am AlarmReceiver,I receive the message");        Intent in = new Intent();        in.setClass(context, StartTiming.class);        in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        context.startActivity(in);    }}


<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.ray.test"      android:versionCode="1"      android:versionName="1.0" android:installLocation="auto">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".StartTiming"                  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="AlarmReceiver">               <intent-filter>                 <action android:name="android.intent.action.STARTMYAP"/>             </intent-filter>        </receiver>    </application></manifest> 
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述
2012-08-31 14:55:20 sparta128 阅读数 106
  • Android 5.x视频课程

    采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。

    79746 人正在学习 去看看 李宁

 

使用AlarmManager和Receiver实现定时自动启动应用程序:

 

public class Main extends Activity {
        public final String MT_ACTION = "android.intent.action.START_MY_APP"; 
        Button bt;
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt = (Button)findViewById(R.id.bt);
        bt.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                                Main.this.finish();
                        }
                });
        AlarmManager am = (AlarmManager)Main.this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(MT_ACTION);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 1);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+3500, pi);
    }
}

 

Manifext:

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.vancl.startapp"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main"
                  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="AlarmReceiver">  
               <intent-filter>  
                 <action android:name="android.intent.action.START_MY_APP"/>  
             </intent-filter>  
        </receiver> 
    </application>
</manifest>
 

 

 

Receiver:

 

 

package com.vancl.startapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
                Intent it = new Intent();
                it.setClass(context, Main.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);	//接受到广播 启动应用
        }

}
 

 


2016-08-23 17:26:32 xyzz609 阅读数 1444
  • Android 5.x视频课程

    采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。

    79746 人正在学习 去看看 李宁

Android之百度云推送(三)如何启动服务端的定时任务

apk和服务端都好了,怎么能定时启动服务呢?
查看了好多资料:
spring task定时器的运用
http://blog.csdn.net/xwygn/article/details/8440692
定时任务实现Timer, TimeTask, ScheduledExecutorService及Spring定时器
http://blog.csdn.net/majinggogogo/article/details/49962081

无耐公司spring版本是2.5的不支持

@Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次  

升级spring试试,原先的项目报错,不值当的改,改动太大了

一共这么几种定时任务,都不行,怎么办

还是自己玩吧,我选择的是线程,

web项目

第一步写个类启动一个线程,并且希望这个类随web服务器启动而启动

PushJob.java

@Component("PushJob")
public class PushJob  extends HttpServlet {  
    private static final long serialVersionUID = 1L;
      @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
          System.out.println("开始 pushjob init .....");
        super.init();
        PushMsg p = new PushMsg();
        Thread t = new Thread(p);
        t.start();
        System.out.println("完成 pushjob init .....");
    }
} 

web.xml进行相应的配置随web服务器启动而启动

    <servlet>
        <servlet-name>PushJob</servlet-name>
        <servlet-class>
            com.ailk.app.push.servlet.PushJob
        </servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

第二步修改AndroidPushBatchUniMsg.java为PushMsg.java

听着很奇怪是吧?看我的

public class PushMsg implements Runnable{
    @Override
    public void run() {
        System.out.println("PushMsg running....");
        while(true){
            doone();
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    private void doone(){
        //原先AndroidPushBatchUniMsg.java的main函数修改
        // 1. get apiKey and secretKey from developer console
        String apiKey = "WnK9iAq465461313GORSyWC";
        String secretKey = "MTVkTFfdsaf443Rgb29hF8d";
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        // 2. build a BaidupushClient object to access released interfaces
        BaiduPushClient pushClient = new BaiduPushClient(pair,
                BaiduPushConstants.CHANNEL_REST_URL);

        // 3. register a YunLogHandler to get detail interacting information
        // in this request.
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            } 
        });

        try {
            System.out.println("开始了吗");
            //从数据库获取消息通知,这个是我自己服务获取的方式,你们改改这就行
            PushBean pb = new PushBean();
            List<PushInfo> pushList=pb.queryPushList(ac);

            System.out.println("有信息吗?"+pushList.size());
            if(pushList.size() > 0){

            for (PushInfo pushBean : pushList)
            {
                // 4. specify request arguments
                //创建Android通知
                JSONObject notification = new JSONObject();
                notification.put("title", pushBean.getTitle());
                notification.put("description",pushBean.getDescs());
                notification.put("notification_builder_id", 0);
                notification.put("notification_basic_style", 4);
                notification.put("open_type", 3);
                JSONObject jsonCustormCont = new JSONObject();
                //自定义内容,key-value

//              jsonCustormCont.put("logStaffCode", "zq");  
//              jsonCustormCont.put("logStaffId", "982985123456");  
//              jsonCustormCont.put("logManagerId", "422493");  
//              jsonCustormCont.put("managerTypeId", "49");  
//              jsonCustormCont.put("logLatnId", "-1");  
//              jsonCustormCont.put("logAreaId", "1");  
//              jsonCustormCont.put("H5Url", "http://www.baidu.com");  
                notification.put("custom_content", jsonCustormCont);                
                String[] channelIds = { "3898756644656267390" };
                PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
                        .addChannelIds(channelIds)
                        .addMsgExpires(new Integer(3600))
                        .addMessageType(1)
                        .addMessage(notification.toString())
                        .addDeviceType(3)
                        .addTopicId(pushBean.getTopicId());// 设置类别主题            
                // 5. http request
                PushBatchUniMsgResponse response = pushClient.pushBatchUniMsg(request);

                // Http请求结果解析打印
                System.out.println(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));

            }

            }

        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                try {
                    throw e;
                } catch (PushClientException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                try {
                    throw e;
                } catch (PushServerException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                System.out.println(String.format(
                        "requestId: %d, errorCode: %d, errorMessage: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我想你应该看出来了,其他的都没动,就是你怎么去数据库拿数据了吧。。不懂得可以加群玩android不是梦 261403514咱们商讨一下

2019-03-20 02:17:07 luckrr 阅读数 139
  • Android 5.x视频课程

    采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。

    79746 人正在学习 去看看 李宁

android8.0以上启动后台服务时会报错,因为8.0以后的版本Google为了避免服务在用户不知情的情况之下做一下偷偷摸摸的事,所以启动规则做了限制,广播也是。

启动服务可以参考以下文章:服务启动

详细一点的可以参考这篇文章;8.0服务启动

下面我做了个demo,实现后台定时发送一个广播,然后在广播中启动服务,

 

服务:

public class Myservice extends Service {
    int anHour = 5*1000;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        Notification notification = new Notification.Builder(this).build();
//        startForeground(0, notification);
        createNotificationChannel();
        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("Myservice --- > 99999988");//这是定时所执行的任务
                Log.e("TAG--->","service");
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime = SystemClock.currentThreadTimeMillis() + anHour;
        Intent intent2 = new Intent();
        intent2.setAction("com.example.action.MyReceiver");
        intent2.setPackage(getPackageName());
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    private void createNotificationChannel() {
        // 通知渠道的id
        String CHANNEL_ID = "my_channel_01";
        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(this)
                .setContentTitle("New Message") .setContentText("You've received new messages.")
//                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setChannelId(CHANNEL_ID)
                .build();
        startForeground(1,notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

}

广播:


public class MyBroadcast extends BroadcastReceiver {
    String TAG = MyBroadcast.class.getName()+"--->";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("TAG--",intent.getAction());
        Intent i = new Intent(context, Myservice.class);
        ContextCompat.startForegroundService(context,i);

        Toast.makeText(context,
                "接收到的Intent的Action为:" + intent.getAction() + "\n 消息内容是:" + intent.getStringExtra("msg"),
                Toast.LENGTH_LONG).show();

    }
}

 

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ganggang.macbook.testmie">

    <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>
        <receiver android:name=".MyBroadcast" >
            <intent-filter >
                <action android:name="com.example.action.MyReceiver"/>
            </intent-filter>
        </receiver>
        <service android:name=".Myservice"></service>
    </application>

</manifest>

 

Main:

public class MainActivity extends Activity {
Button send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取程序界面中的按钮
//        views();
        Intent i = new Intent(this, Myservice.class);
        ContextCompat.startForegroundService(this,i);

    }
    private void views(){
        send = (Button)findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //创建Intent
                Intent intent = new Intent();
                intent.setAction("com.example.action.MyReceiver");
                intent.setPackage(getPackageName());
                intent.putExtra("msg", "简单的消息");
                //发送广播
                sendBroadcast(intent);
            }
        });
    }
}

 

2012-08-29 10:44:42 huangbowen_java 阅读数 37
  • Android 5.x视频课程

    采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。

    79746 人正在学习 去看看 李宁

因为在项目中需要定时启动后台服务做一些操作,我不想用线程,就直接写了个定时器。

没有更多推荐了,返回首页